-3

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.

ikegami
  • 367,544
  • 15
  • 269
  • 518
Rajni Sah
  • 1
  • 1
  • 1
    Re "*The function call statements in Line x do not execute.*", This is easily disproved by adding `warn("!");` inside of `funcIsPrime`. What problem are you actually having? – ikegami Aug 09 '18 at 05:51
  • 3
    Always use `use strict; use warnings qw( all );`! – ikegami Aug 09 '18 at 06:33

1 Answers1

1

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
ggorlen
  • 44,755
  • 7
  • 76
  • 106
  • 1
    Did you mean: `my $i = int sqrt($num)`? – melpomene Aug 09 '18 at 06:08
  • `int sqrt $num` can give you a number less than the one you expect because of floating point error, so `my $i = 1 + int sqrt $num` would be safer. – ikegami Aug 09 '18 at 06:33
  • Thank a lot. It worked. I got where I had gone wrong. – Rajni Sah Aug 09 '18 at 07:15
  • @ikegami I considered that--I used my sub to solve [PE #7](https://projecteuler.net/problem=7) as a basic test and it was accurate. Do you have an example of an input it fails on? If so, I'll change it. I can see I probably should have left it same as OP instead of attempting to head down the optimization wormhole :) – ggorlen Aug 09 '18 at 16:19
  • @ggorlen, My math library appears to be very smart and returns the exact integer --not a billionths above or below-- for sqrt(n^2) for integers n=1..100. There's no saying that other math libraries are that smart. though – ikegami Aug 09 '18 at 20:34