Search code examples
javaalgorithmintegerpalindrome

Find the biggest palindrome in multiple integers


I have a problem with some algorithm. I must write a java app, which find the biggest palindrome for the product of a predetermined amount of numbers (l) of a predetermined number of digits (n). For example for l=2 and n=2 the biggest palindrome is 9009 (91 * 99).

A palindrome checker I was writed, but I have no idea how to multiply the appropriate amount of numbers with a given number of digits.

Can anybody help me?

Sorry for my English.


Solution

  • Here is possible implementation of iteration through all combinations of l numbers with n digits:

    public static int[] iterate(int l, int n) {
        int minNum = (int) Math.pow(10, n - 1);
        int maxNum = (int) Math.pow(10, n) - 1;
        // init array with `l` numbers with `maxNum` value
        int[] numbers = new int[l];
        Arrays.fill(numbers, maxNum);
        // iterate through all combinations of numbers
        while (true) {
            System.out.println(Arrays.toString(numbers)); // for debug only
            // calc multiplication of current combination of numbers
            long mul = 1;
            for (int num : numbers) {
                mul *= num;
            }
            if (isPalindrome(mul)) {
                return numbers; // biggest palindrome found
            }
            // calc next combination of numbers
            boolean allMaxNums = true;
            for (int j = l - 1; j >= 0; --j) {
                --numbers[j];
                if (numbers[j] < minNum) {
                    numbers[j] = maxNum; // need to reduce next number, go to the next j
                } else {
                    // now all numbers in [minNum, maxNum] bounds
                    allMaxNums = false;
                    break;
                }
            }
            if (allMaxNums) {
                break; // returned to the initial combination
            }
        }
        return null; // palindrome not found
    }
    
    private static boolean isPalindrome(long mul) {
        // your check here
        return false;
    }
    

    EDIT

    Unfortunately my previous solution is not right, we must iterate over combinations of numbers in descending order of its' products (not in some other order as i have done). I think that working code is better then my сhaotic explanations, so you can see my new solution here: https://ideone.com/ZSQC5d.