Skip to content

Instantly share code, notes, and snippets.

@gzmask
Created June 19, 2012 21:16
Show Gist options
  • Select an option

  • Save gzmask/2956578 to your computer and use it in GitHub Desktop.

Select an option

Save gzmask/2956578 to your computer and use it in GitHub Desktop.
project euler Problem 3
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
@gzmask

gzmask commented Jun 20, 2012

Copy link
Copy Markdown
Author

Thanks. This function works with small numbers. But for 600851475143 I got "memory allocation failed".

@MgaMPKAy

Copy link
Copy Markdown

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

@gzmask

gzmask commented Jun 21, 2012

Copy link
Copy Markdown
Author

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