Last active
December 11, 2015 08:58
-
-
Save zerosum/4576553 to your computer and use it in GitHub Desktop.
Project Euler: Problem 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from math import sqrt, ceil | |
def sieve(numbers): | |
primes = [] | |
while(len(numbers) > 0): | |
prime = numbers.pop(0) | |
primes.append(prime) | |
numbers = [a for a in numbers if a%prime!=0] | |
return primes | |
def largiest_prime_factor(n): | |
primes = sieve(range(2, int(ceil(sqrt(n))))) | |
while(len(primes) > 0): | |
prime = primes.pop() | |
if(n%prime==0): | |
return prime | |
print largiest_prime_factor(600851475143) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object Euler0003 { | |
def main(args: Array[String]): Unit = { | |
println(largiest_prime_factor(600851475143L)) | |
} | |
private def largiest_prime_factor(n: Long) = { | |
sieve((2 to Math.sqrt(n).toInt).toList).filter(n%_==0).max | |
} | |
private def sieve(numbers: List[Int]): List[Int] = { | |
sieve(numbers, Nil) | |
} | |
private def sieve(numbers: List[Int], primes: List[Int]): List[Int] = { | |
if(numbers.isEmpty) { | |
primes | |
} else { | |
val h = numbers.head | |
sieve(numbers.tail.filter(_%h != 0), h :: primes) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment