Project Euler 4: Largest Palindromic Number with 6 Figures
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.
There is probably an elegant way of doing this, but I prefer the easier method of brute force. This is a Perl script that calculates every product of three-digit numbers and saves all of the palindromic numbers in a list. It then sorts the list in descending numerical order and prints the first element in the list.
1 2 3 4 5 6 7 8 9 10 | my @l; # the list for all the palindrom numbers for ( my $n = 999; $n > 99; $n-- ) { # do for 100 to 999 for ( my $m = $n; $m > 99; $m-- ) { # do for 100 to $n if ( $n*$m == reverse( $n*$m ) ) { # if the product is a palindrom.. push @l, $n*$m; # ..add it to the list } } } @l = sort { $b <=> $a } @l; # sort @l numerically with the largest number first print $l[0]; # print the first element (the largest number) |
The script finishes in about a second. Note line 3, the second for loop. Since $n times the numbers higher than $n have already been multiplied earlier in the loop, these can be left out to save time.

I kind of did it the same way.. Works perfectly when I change the parameters for the 2 digit products, but for the 3 it doesn’t…
I paste only the important parts of code, it doesn’t have any syntax problems anyway, runs perfectly, the problem must be logical, cause the result is wrong…:
p=1;
for(i=999;i>99;i–)
for(j=999;j>99;j–)
{
g=i*j;
printf(”%d * %d = %ld\n”,i,j,g);
ltoa(g,str,10);
//ltoa is a ready function I found that does the same as //itoa, but for long integer
l=strlen(str);
count=0;
for(k=0;k
Comment by Anastasi — January 3, 2008 @ 4:57 pm
seems I have a limit to the characters of the comment, so I paste again the rest of the code that is not seen:
for(k=0;k
Comment by Anastasia — January 3, 2008 @ 5:00 pm
You might as well be writing c, if you aren’t going to take advantage of Perl’s idioms.
Comment by ajm — April 24, 2008 @ 5:45 pm