in reply to Largest palindrome number for a 3 digit product of 2 numbers

# file pal.pl my $d = shift; my ($p, $n, @r); my $r1 = - (9 x $d); my $r2 = - ((9 x ($d-1)) +1); IT: for my $f ($r1 .. $r2 ) { for ($f .. $r2) { $p = $f * $_; last if $p < $r[2]; if ($p eq reverse $p) { if ($n < $p) { $n = $p; @r = ($f,$_,$p); next IT; } } } last if -$f**2 < $r[2]; } print -$r[0]," * ",-$r[1]," = $r[2]\n"; __END__ 993 * 913 = 906609
qwurx [shmem] ~> time perl pal.pl 3 993 * 913 = 906609 real 0m0.004s user 0m0.000s sys 0m0.000s
perl -le'print map{pack c,($-++?1:13)+ord}split//,ESEL'

Replies are listed 'Best First'.
Re^2: Largest palindrome number for a 3 digit product of 2 numbers
by pr33 (Scribe) on Jul 06, 2017 at 05:59 UTC

    Thanks . So you are checking the condition if the Square of the Number is less than the current product found in the second statement of the last

      Yes. If the square of the greater operand is smaller than the highest palindrome found, further rundown of either factor can be stopped. There is no higher number to be found.

      My algorithm differs from salvas solution, which probes the highest factors for a valid product, while mine runs down one factor to its lowest value. For some amount of digits it turns out to be faster than salva's, for others it is much, much slower (e.g. 9 digits).

      update: Another approach would be:

      • Starting from the square of the highest number, construct the next lower palindrome number
      • factorize that number
      • check for any cobination of factors whether their product has the amount of digits wanted
      • check if the remaining factors product also has the amount of digits wanted
      • If so, stop there. Highest palindrome found.

      I guess that for a large amount of digits this might be the fastest way.

      perl -le'print map{pack c,($-++?1:13)+ord}split//,ESEL'