HomePage RecentChanges Define

euler35.lhs

The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.

There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.

How many circular primes are there below one million?

> divisors :: Int -> [Int]
> divisors n = 
>     let
>         sq = floor $ sqrt (fromIntegral n) 
>         dd1 = (foldl (\l m -> if n `mod` m == 0 then m:l else l) [] (2:[3,5..sq]))
>     in
>       dd1


> ndivisors :: Int -> Int
> ndivisors = length . divisors

> primes = filter (\i -> ndivisors i == 0)

> rotations :: Int -> [Char] -> [[Char]]
> rotations 0 xs = [xs]
> rotations n xs@(h:t) = xs:(rotations (n-1) (t++[h])) 

> checkRotations :: Int -> Bool
> checkRotations n = 
>     let
>         sn = show n 
>         rots = map read $ rotations (length sn) sn :: [Int]
>     in
>       all (\n -> ndivisors n == 0) rots 

> main = putStrLn $ show $ length $ filter checkRotations $ primes [2..1000000]