euler 37

Nov. 20th, 2012 10:57 pm
[personal profile] sassa_nf
а что, товарищи, скажете - коряво получилось или ничего?


primes = 2: [p | p <- [3,5..], isPrime p]

isPrime x = x > 1 && foldr (\p n -> tooLarge p || (x `mod` p /= 0 && n)) True primes
  where tooLarge = ((sqrt $ fromIntegral x) + 0.1 <=) . fromIntegral

toDigits = map (`mod` 10) . rTrunc

rTrunc = takeWhile (>0) . iterate (`div` 10)

trunc = filter g $ concat $ takeWhile (not . null) $ tail $ iterate f p10
  where f ps = [p | y <- ys, x <- ps,  -- here we construct lists of left-truncatable primes that may produce right-truncatable primes (ie excluding those that can't produce right-truncatable primes)
                    let d = (10^) $ length $ toDigits $ head ps,
                    let p = x+y*d,
                    odd y && isPrime p || g p] -- don't let the 2 appear in the middle of the number, i.e. g p must hold; otherwise, the digits are permitted to appear in the middle, not producing (g p) at this time; this condition alone makes the series converge
        g = all isPrime . rTrunc
        p10 = takeWhile (<10) primes
        ys = [1,2,3,5,7,9] -- digits that may produce right-truncatable primes; could use the whole range [1..9], but all even except 2 cannot pass (g p) test

main = putStr $ show $ sum $ trunc

Profile

sassa_nf

February 2026

S M T W T F S
1234567
891011121314
15161718192021
222324252627 28

Style Credit

Expand Cut Tags

No cut tags
Page generated May. 22nd, 2026 07:03 am
Powered by Dreamwidth Studios