Home > Software design >  Can someone explain how Dmitry got the NMin math down?
Can someone explain how Dmitry got the NMin math down?

Time:05-21

The original problem is located at Project Euler Largest palindrome product and is below.

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers.

The question in context is found at Dmitry Answering Largest palindrome product - C#. I got the correct answer but did it from min to max instead of max to min so I looked for a more efficient answer to study. I understand what all the code does, but I can't figure out where Dmitry started to get the formula to get the minimum multiplicand from the maximum multiplicand constant. I'm blitzing through several coding challenge websites in preparation for some technical interviews.

This line:

const int NMin = NMax - (NMax   1) / 10   1;

OF

// Store the maximum palindrome number here:
long maxNumber = 0;

// The maximum multiplicand (typically: 9...9):
const int NMax = 999;
// The minimum multiplicand.
// Obviously, it couldn't be less than 90...0:
const int NMin = NMax - (NMax   1) / 10   1;

for (int i = NMax; i > NMin; i--)
{
    // Starting from i since i * j = j * i for any i, j:
    for (int j = i; j > NMin; j--)
    {
        long number = Math.BigMul(i, j);
        // The fastest condition should be the first in the `if` statement:
        if (number > maxNumber && isPalindome(number))
        {
            maxNumber = number;
            Console.WriteLine("{0} = {1} * {2}", number, i, j);
            break; // Leave the `j` loop, because it's guaranteed that there is
                   // no numbers greater than `number` for the current `i`
        }
    }
}

The websites I've been going through include:

CodePudding user response:

As stated in problem 4 the largest palindrome for the product of two-digit numbers is 91*99. I believe Dmitry recognized that of all max palindromes for a given digit range (3, 4, or 5 as he calculated but realistically to infinity) must be 9x -> 9y (where x represents 0's and y represents 9's). The amount of x and y needed is digit - 1 if you always want the highest palindrome. The lower 90% here is simply not worth checking for palindromes because they won't produce the highest multiplication.

Thus he can calculate the minimum every time given the equation he provided:

NMin = NMax - (NMax   1) / 10   1 // NMin = 900 if NMax = 999

In the case of 4-digit palindrome, this produces 9,000 -> 9,999 or 90,000 -> 99,999 for 5.

The important thing to note here is he could have hard-coded NMin or picked a larger minimum number.

  • Related