Search code examples
perlloopssubroutine

Perl subroutine not working in loop


I tried writing a simple code to find whether a number can be expressed as the sum of primes or not, in Perl. The sample code is as shown:

sub funcIsPrime {
    my $num = $_[0];    
    my $isPrime = 1;
    for($i= 2; $i <= $num/2; $i++){
        if($num%$i == 0){
            $isPrime = 0;
            last;
        }
    }
    return $isPrime;
}

#my $num = <>;
my $num = 20;
for($i = 2; $i <= $num/2; $i++){
    print "$i\t";
    my $j = $num-$i;
    print "$j\n";

    if(funcIsPrime($i) and funcIsPrime($j)){    # Line x
        print "$num = $i + $j\n";
    }
}

The function call statements in Line x do not execute. The same line when put outside the loop works fine. What can be the possible solution? Please help. Thank you.


Solution

  • The main issue is missing my in variable declarations. Perl won't let you run the program if you include use warnings; and use strict;:

    Global symbol "$i" requires explicit package name (did you forget to declare "my $i"?) at test.pl line 22.
    Execution of test.pl aborted due to compilation errors.
    

    Here's simplified working code (you can search for factors up to the square root of n, by the way, although this isn't a perfect or efficient prime test by any means):

    use strict;
    use warnings;
    
    sub isPrime {
        my $num = $_[0];    
    
        for (my $i = int sqrt $num; $i > 1; $i--) {
            if ($num % $i == 0) {
                return 0;
            }
        }
    
        return 1;
    }
    
    my $num = 20;
    
    for (my $i = 2; $i <= $num / 2; $i++) {
        my $j = $num - $i;
    
        if (isPrime($i) && isPrime($j)) {
            print "$num = $i + $j\n";
        }
    }
    

    Output

    20 = 3 + 17
    20 = 7 + 13