Created
June 22, 2018 11:18
-
-
Save cppxor2arr/c868d5aabd71982d85867abaeb3653e1 to your computer and use it in GitHub Desktop.
primes
This file contains hidden or 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
module Main where | |
import Data.List (genericTake) | |
{- | |
let p(i) be the i(th) prime number starting from 2 | |
[p1,p2,p3,p4,p5...] | |
[(p2-p1),(p3-p2),(p4-p3),(p5-p4)...] | |
[{(p3-p2)-(p2-p1)},{(p4-p3)-(p3-p2)},{(p5-p4)-(p4-p3)}...] | |
... etc. applied n times | |
-} | |
main :: IO() | |
main = do | |
-- input format: "a b" | |
input <- getLine | |
let args = words input | |
a = read (head args) :: Integer | |
b = read (last args) :: Integer | |
print . applyN a seqDiff . primes $ b | |
-- applyN n f == (f . f . f...n times) | |
applyN :: Integral a => a -> (b -> b) -> b -> b | |
applyN n f x | |
| n > 0 = applyN (n-1) f $ f x | |
| otherwise = x | |
-- seqDiff [x1,x2,x3...] == [x2-x1,x3-x2...] | |
seqDiff :: Num a => [a] -> [a] | |
seqDiff [] = [] | |
seqDiff [x] = [] | |
seqDiff [x1,x2] = [x2-x1] | |
seqDiff (x1:x2:xs) = x2-x1:seqDiff (x2:xs) | |
-- primes n == [p1,p2,p3...nth prime] | |
primes :: Integral a => a -> [a] | |
primes n = genericTake n . filterPrime $ [2..] | |
where filterPrime (p:xs) = | |
p : filterPrime (filter (\x -> x `mod` p /= 0) xs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment