Project Euler #160: Factorial trailing digits

  • + 0 comments

    Hi, can someone help me with the code? I am able to pass all test cases that I enter manually. Tried with 22b16, 22b10, 20b10, 20b16, 10b10, 10b9, 22b2 etc. However, the code is only passing testcase 0;

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        Scanner scan = new Scanner(System.in);
        int b = scan.nextInt();
        int q = scan.nextInt();
        for(int i = 0; i < q; i++)
        {
            int n = scan.nextInt();
            long ans = factorial(n, b);
            System.out.println(toBase(ans, b));
        }
    }
    public static long factorial(int n, int b)
    {
        long ans = 1; int digits5 = b*b*b*b*b;
        for(int i = 2; i <= n; i++)
        {
            ans = ans * i;
            // remove trailing zeros
            while(true){ if(ans % b == 0) ans = ans/b; else break;}
            // keep only last 5 digits
            ans = ans % digits5;
        }
        return ans;
    }
    static char[] bases = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 
                    'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
    public static String toBase(long ans, int base)
    {
        char[] digits = new char[20]; int count = 0;
        for(int i = 0; i < 20; i++)
        {
            int k = (int) (ans % base);
            digits[i] = bases[k]; ans = ans / base; count++;
            if(ans < base) {digits[i+1] = bases[(int) ans]; count++; break;}
        }
        char[] digitNew = new char[count];
        // need to reverse digits
        for(int j = 0; j < count; j++)
            digitNew[count-1-j] = digits[j];
        return new String(digitNew);
    }