Search code examples
perlpalindrome

Perl - finding the largest palindrome product


I started learning perl recently and I wrote this code to find the largest palindrome product that can be obtained by multiplying 2 3-digit numbers. (question here: https://projecteuler.net/problem=4 )

Here is the code:

#!/usr/bin/perl
use 5.010;

sub checkpal{
    for ($k=0;$k<length($_[0]);$k++){$b = substr ($_[0], $k, 1).$b;}
    if ($_[0] eq $b){1}else{0}
}

$pals = $numb1 = undef;

for ($i = 998001; $i>=10000; $i--){
    if (&checkpal($i)){
    for ($j = 100; $j <1000; $j++){
        if ( !($i % $j) && (length $j == 3) ){$numb1 = $j; $pals = $i; last;}
    }
    }
    if (defined $numb1){last}
}

say $numb1."     ".($pals/$numb1);

My idea is quite simple. It simply goes through a loop starting from 998001 (the largest value that product of 2 3-digit number can have) and check if the value is palindrome. If it is a palindrome, it goes through another loop to check if it can be obtained by multiplying 2 three digit numbers. Now, this algorithm might not be the most efficient or the best in the world, it should at least give the result. Which it isn't.

The problem isn't in the subroutine checkpal as far as I know. But the if (&checkblock($i)) block doesn't get executed even when $i is a palindrome. And I don't know why. Sorry if it is obvious or something .. but please tell me why it isn't working?


Solution

  • if ( !($i % $j) and length($i/$j)==3) { .. }
    

    instead of

    if ( !($i % $j) && (length $j == 3) )
    

    as you want to check whether $i/$j has three digits, not $j which goes anyway from 100 to 999.

    As a side-note,

    if (checkpal($i))
    

    can be replaced with simple

    if ($i eq reverse $i)