Ask and Learn
Ask and Learn

Reputation: 8959

segmentation fault in perl grep function

working on Euler problem 3

The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?

here is my Perl code just try to get all the factors first but it got segmentation fault, my Perl age is just about 2 month, could not figure out why. Segmentation fault 11 when I run it.

 #!/usr/bin/perl
 use warnings; 
 use strict;

 my $number = 600851475143;
 my @factors = grep {$number % $_ == 0} (1..$number);
 print @factors;

Run it again with sudo, no more segmentation fault but nothing printed out.

Upvotes: 0

Views: 190

Answers (1)

Miller
Miller

Reputation: 35198

Code from googling "euler problem 3" and translating the python code.

use strict;
use warnings;

sub largest_prime_factor {
    my $n = shift;

    my $largest_factor = 1;

    # remove any factors of 2 first
    while ($n % 2 == 0) {
        $largest_factor = 2;
        $n /= 2;
    }

    # now look at odd factors
    my $p = 3;
    while ($n != 1) {
        while ($n % $p == 0) {
            $largest_factor = $p;
            $n /= $p;
        }
        $p += 2
    }

    return $largest_factor
}

print largest_prime_factor(600851475143);

1;

__END__

Or relying on good ole cpan:

use Math::Prime::Util qw(factor);
use List::Util qw(max);

use strict;
use warnings;

print max factor(600851475143);

Upvotes: 3

Related Questions