Find the largest palindrome made from the product of two 3-digit numbers - Javascript

前端 未结 21 1529
感情败类
感情败类 2020-12-28 17:16

Can anyone tell me what\'s wrong with the code. Find the largest palindrome made from the product of two 3-digit numbers.

function largestPalind         


        
21条回答
  •  余生分开走
    2020-12-28 17:46

    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 so then is there a solution where ab > 1000 and 1000(a+b) - ab < 93391 ? There is not :)

提交回复
热议问题