Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • find the largest palindrome made from the product of 3 digit numbers java

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 319
    Answer it

    Can some one please explain what is done in the following code.

    I found it in in Stack overflow.  I asked the question in the same web site and got the following reply Stackoverflow isn't meant for the purpose of explaining code . Since I am novice can someone help me.e The link for the same is provided in the message


    I think if you apply maths to the problem you can decrease the guesswork really significantly.

    I will write the three digit numbers as 1000 - a and 1000 - b which means the palindrome is 1 000 000 - 1000(a+b) + ab.

    First, let's find solutions where ab < 1000. Then the three leftmost digits are 1000 - (a+b) and the three rightmost digits are ab.

    Then I will say this is a palindrome with digits x,y,z:

    100x+10y+z=ab
    100z+10y+x=1000-a-b
    thus

    99x-99z = ab+a+b-1000
    x-z = 1/99(ab+a+b-10)-10
    So then (ab+a+b-10) is divisible by 99 and we also know that x and z being digits the left side is between -9 and 0 (the whole shebang is symmetrical so we can presume x <= z) so then 1/99(ab+a+b-10) is between 1 and 9. We can rewrite ab+a+b-10 as ab+a+b+1-11=99p so (a+1)(b+1)=99p+11=11*(9p+1) where p runs between 1 and 9. That's really easy:

    for ($p = 1; $p <= 9; $p++) {
     $n = 9 * $p + 1;
     // This could be vastly optimized further.
     for ($j = 1; $j <= $n; $j++) {
       if ($n % $j === 0) {
         $a = 1001 - $n / $j;
         $b = 1001 - 11 * $j;
         $test = $a * $b;
         if (strrev($test) === (string) $test) {
           print "$a $b " . $a * $b . "\n";
         }
       }
     }
    }
    Now this prints only one solution which is the correct one.

    Now we know 906609 is a solution


     

     

     

 0 Answer(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: