Created
June 19, 2012 21:16
-
-
Save gzmask/2956578 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
num = 600851475143 | |
nums = reverse [1..600851475143] | |
isPrime :: (Integral a) => a -> Bool | |
isPrime x = (product $ map (mod x) [2..(x-1)]) /= 0 | |
getPrimes :: (Integral a) => [a] -> [a] | |
getPrimes xs = filter isPrime $ xs | |
primes = getPrimes nums | |
isFactor :: (Integral a) => a -> a -> Bool | |
isFactor x y = (mod x y) == 0 | |
largestPrimeFactor = find (isFactor num) $ primes |
Thanks. This function works with small numbers. But for 600851475143 I got "memory allocation failed".
You shuold modify your isPrime
too.
Here is mine:
isPrime 2 = True
isPrime n = and [ n `rem` x /= 0 | x <- [2.. ceiling $ sqrt $ fromIntegral n]]
$ time ./Prime
6857
real 0m0.049s
user 0m0.043s
sys 0m0.003s
thanks! "and" is short-circuit and use sqrt to reduce n to sqrt(n). this works.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Beacuse you reverse the the list
[1..600851475143]
, the runtime system has to build up the entire reversed list before processing.Your
isPrime
is slow too, because*
ofInt
andInteger
is not a short-circuit operator, andproduct
is implemented using*
.And this is my attemp, imperative and ugly.