0

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.

6
  • Yea, deleted that print code Commented Feb 28, 2014 at 3:03
  • (1..$number) will generate an 2T array. Are you using a 64-bit OS? Commented Feb 28, 2014 at 3:07
  • Yes, Mac OS X 10.8.5, perlbrew Perl 5.18.2. Tried bigint as well, did not make any difference. Commented Feb 28, 2014 at 3:10
  • 1
    I guess it is still because you are trying to allocate too many memories. Commented Feb 28, 2014 at 3:25
  • agreed, even after I removed last 3 digits (so 1000 times smaller). It printed out "Out of Memory!" on my Linux VM, used all my remaining 12G RAM on my MacBook Pro. Will try something else Commented Feb 28, 2014 at 3:45

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

CPAN solution slightly easier now: perl -E 'use ntheory ":all"; say vecmax(factor(600851475143));'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.