Skip to content

Instantly share code, notes, and snippets.

@RavuAlHemio
Last active August 29, 2015 14:08
Show Gist options
  • Save RavuAlHemio/3efbfc49f3fb20edbbca to your computer and use it in GitHub Desktop.
Save RavuAlHemio/3efbfc49f3fb20edbbca to your computer and use it in GitHub Desktop.
tightPrimeEmbedding
import Data.List (find)
import Data.Maybe (fromJust)
isPrime :: Integer -> Bool
isPrime n
-- negative numbers, 0 and 1 are not prime
| n < 2 = False
-- 2 is prime, all other numbers divisible by 2 aren't
| n == 2 = True
| n `mod` 2 == 0 = False
| otherwise = not $ any ((\t i -> t `mod` i == 0) n) [2 .. maxToTest]
where
maxToTest = (floor . sqrt . fromInteger) n
tightPrimeEmbedding :: Integer -> (Integer, Integer, Integer)
tightPrimeEmbedding n
| n < 2 = error "need an integer greater than 1"
| otherwise = (before, n, after)
where
before = fromJust $ find (isPrime) [n, (n-1) .. 2]
after = fromJust $ find (isPrime) [(n+1), (n+2) ..]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment