Skip to content

Instantly share code, notes, and snippets.

@gideondsouza
Created January 26, 2013 14:32
Show Gist options
  • Save gideondsouza/4642727 to your computer and use it in GitHub Desktop.
Save gideondsouza/4642727 to your computer and use it in GitHub Desktop.
Created by www.tryperl.com. Updated on 26-0-113 at 20 hour(s)
#!/usr/bin/perl
# Solution to projecteuler.net/problem=3
# Question:
# The prime factors of 13195 are 5, 7, 13 and 29.
# What is the largest prime factor of the number 600851475143 ?
# Answer: 6857
use strict;
use warnings;
my @factors;
getFactors(600851475143);
my %seen;
my @unique = grep { ! $seen{$_}++ } @factors;
foreach my $x (@unique) {
print "$x\n"
}
sub getFactors {
my $n = shift;
if($n<1) {return;}
if(isPrime($n)){
push @factors, $n;
return;
}
for (my $d = 2; $d <= ($n-1); $d++)
{
if($n % $d == 0)
{
push @factors, $d;
getFactors(int($n/$d));
last;
}
}
}
sub isPrime {
my $n = shift;
my $c = 0;
for (my $i = 1; $i < $n; $i++) {
if(($n % $i) == 0)
{
$c++;
if($c > 1)
{
return 0;
}
}
}
if($c == 1)
{
return 1;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment