Skip to content

Instantly share code, notes, and snippets.

@sooop
Created May 11, 2015 09:39
Show Gist options
  • Save sooop/0d379896a70a2e0c7335 to your computer and use it in GitHub Desktop.
Save sooop/0d379896a70a2e0c7335 to your computer and use it in GitHub Desktop.
isPrime :: (Integral a) => a -> Bool
isPrime 2 = True
isPrime 3 = True
isPrime x
| x < 2 = False
| x `mod` 2 == 0 = False
| x `mod` 3 ==0 = False
| x < 9 = True
| otherwise = let l = floor (sqrt (fromIntegral x))
in isPrimeHelper x l 5
isPrimeHelper :: (Integral a) => a -> a -> a -> Bool
isPrimeHelper x l k
| k > l = True
| x `mod` k == 0 = False
| x `mod` (k + 2) == 0 = False
| otherwise = isPrimeHelper x l (k + 6)
main = print $ isPrime 107
@stripe-q
Copy link

소수인지 검사하는 함수.

오일러 프로젝트의 "2백만 이하의 소수의 합"을 구하는 문제에서는

main = print $ sum $ takeWhile (<= 2000000) [x | x <- [1..], isPrime x]

로 풀 수 있다.

GHCI에서는 상당히 오랜 시간이 걸리지만,
컴파일해서 돌려보면 2초 내외로 답이 나옴.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment