简体   繁体   中英

Cutting of the first 9 digits

Alright I am trying to solve a challenge one of my friends gave me to do, well I've manged to cut the last 9 digits out of a BigInteger well I had a way to cut-off the first 9 but it was so slow, it was taking too long.

The reason I need the first 9 and the last 9 is because I am looking for a BigInteger where the first and last are pandigital.

If you do not understand what I mean say we have n = new BigInteger("123456789987654321") well I need to get the "123456789" and the "987654321" seperately, and I do NOT want to convert the BigInteger to a string because that's a VERY slow process.

I am going for speed here, I am just stumped on this solution. I've heard something about using the Golden Ratio? Here is my code if you're interested.

import java.math.BigInteger;

public class Main {

    public static void main(String...strings)
    {       
        long timeStart = System.currentTimeMillis();
        fib(350_000);
        long timeEnd = System.currentTimeMillis();
        System.out.println("Finished processing, time: " + (timeEnd - timeStart) + " milliseconds.");
    }

    public static BigInteger fib(int n)
    {
        BigInteger prev1 = BigInteger.valueOf(0), prev2 = BigInteger.valueOf(1);        
        for (int i = 0; i < n; i++)
        {   

            // TODO: Check if the head is pandigital as well.
            BigInteger tailing9Digits = tailing9Digits(prev1);
            boolean tailPandigital = isPanDigital(tailing9Digits);

            if (tailPandigital)
            {                   
                System.out.println("Solved at index: " + i);
                break;
            }
            BigInteger savePrev1 = prev1;
            prev1 = prev2;
            prev2 = savePrev1.add(prev2);
        }
        return prev1;
    }

    public static BigInteger leading9Digits(BigInteger x)
    {
        // STUCK HERE.
        return null;
    }

    public static BigInteger tailing9Digits(BigInteger x) 
    {
        return x.remainder(BigInteger.TEN.pow(9));
    }

    static BigInteger[] pows = new BigInteger[16];

    static 
    {
        for (int i = 0; i < 16; i++) 
        {
            pows[i] = BigInteger.TEN.pow(i);
        }
    }

    static boolean isPanDigital(BigInteger n) 
    {
        if (!n.remainder(BigInteger.valueOf(9)).equals(BigInteger.ZERO)) 
        {
            return false;
        }
        boolean[] foundDigits = new boolean[9];


        boolean isPanDigital = true;
        for (int i = 1; i <= 9; i++) 
        {
            BigInteger digit = n.remainder(pows[i]).divide(pows[i - 1]);
            for (int j = 0; j < foundDigits.length; j++) {
                if (digit.equals(BigInteger.valueOf(j + 1)) && !foundDigits[j])
                {
                    foundDigits[j] = true;
                }
            }
        }

        for (int i = 0; i < 9; i++)
        {
            isPanDigital = isPanDigital && foundDigits[i];
        }

        return isPanDigital;
    }
}

BigInteger isn't something I'd recommend using if you care at all about speed. Most of its methods are poorly-implemented, and this typically results in very slow code.

There's a divide-and-conquer trick for division and radix conversion that you might find helpful.

First, BigInteger 's multiply() is quadratic. You'll need to work around that, otherwise these divide-and-conquer tricks won't lead to any speedup. Multiplication via the fast Fourier transform is reasonably fast and good.

If you want to convert a BigInteger to base 10, break it in half (bitwise) and write it as a * 256^k + b. One thing you can do is convert a and b to base-10 recursively, then convert 256^k to decimal by repeated squaring, and then, in base 10, multiply a by 256^k and add b to the result. Also, since you're only interested in the first few digits, you might not even need to convert b if the first few digits of a * 256^k can't possibly be influenced by adding something as small as b .

A similar trick works for division.

You can do bit-shifting and extraction using the toByteArray() method.

Maybe this is not too fast but at least it's simple

    BigInteger n = new BigInteger("123456789987654321");
    BigInteger n2 = n.divide(BigInteger.TEN.pow(new BigDecimal(n).precision() - 9));
    BigInteger n1 = n.remainder(new BigInteger("1000000000"));
    System.out.println(n1);
    System.out.println(n2);

output

987654321
123456789

Well I believe this is what you need:

import java.math.BigInteger;

public class PandigitalCheck {

    public static void main(String[] args) {

        BigInteger num = new BigInteger("12345678907438297438924239987654321");
        long timeStart = System.currentTimeMillis();
        System.out.println("Is Pandigital: " + isPandigital(num));
        long timeEnd = System.currentTimeMillis();
        System.out.println("Time Taken: " + (timeEnd - timeStart) + " ms");
    }

    private static boolean isPandigital(BigInteger num) {
        if (getTrailing9Digits(num).compareTo(getLeading9Digits(num)) == 0) {
            return true;
        }

        return false;
    }

    private static BigInteger getLeading9Digits(BigInteger num) {
        int length = getBigIntLength(num);
        BigInteger leading9 = BigInteger.ZERO;
        for (int i = 0; i < 9; i++) {
            BigInteger remainder = num.divide(BigInteger.TEN.pow(length - 1 - i));
            leading9 = leading9.add(remainder.multiply(BigInteger.TEN.pow(i)));
            num = num.remainder(BigInteger.TEN.pow(length - 1 - i));
        }

        return leading9;
    }

    private static int getBigIntLength(BigInteger num) {
        for (int i = 1; ; i++) {
            if (num.divide(BigInteger.TEN.pow(i)) == BigInteger.ZERO) {
                return i;
            }
        }
    }

    private static BigInteger getTrailing9Digits(BigInteger num) {
        return num.remainder(BigInteger.TEN.pow(9));
    }

}

The output is:

Is Pandigital: true
Time Taken: 0 ms

Does it fit the bill?

I'm newbie for java, I'm converting BigInteger to String only but it's little bit fast as your code

import java.math.BigInteger;
public class Main {
    public static void main(String args[])
    {       
        long timeStart = System.currentTimeMillis();
        String biStr = new BigInteger("123456789987654321").toString();
        int length=(biStr.length())/2;
        String[] ints = new String[length];
        String[] ints2 = new String[length];
        for(int i=0; i<length; i++) {
            int j=i+length;
            ints[i] = String.valueOf(biStr.charAt(i));
            ints2[i] = String.valueOf(biStr.charAt(j));
            System.out.println(ints[i] +"  |  "+ints2[i]);
        }
        long timeEnd = System.currentTimeMillis();
        System.out.println("Finished processing, time: " + (timeEnd - timeStart) + " milliseconds.");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM