0

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.

Woytas
  • 5
  • 1
  • 2
    I think you are trying to solve project euler problem. You can have a look at http://stackoverflow.com/questions/24772179/largest-palindrome-product-euler-project/24772340#24772340 – Sanjeev Kumar Aug 31 '15 at 14:18
  • Yes, but I have to do it for any amount of numbers with a given number of digits. So it needs to work for both the two-digit numbers, three-digit, four-digit, etc. and additionally it may be multiplication for two, three, four, etc. numbers – Woytas Aug 31 '15 at 15:19

1 Answers1

0

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.

Aleksei Shestakov
  • 2,508
  • 2
  • 13
  • 14