Skip to content

Project Euler Problem 37

November 22, 2011

Again reusing for Project Euler Problem 37 solution developments in prime numbers generation from Project Euler Problem 10 solution the rest of solution is trivial: filter primes sequence on truncatable property and take first 11 members.

open System

#nowarn "40"

let rec primes = 
    Seq.cache <| seq { yield 2; yield! Seq.unfold nextPrime 3 }
and nextPrime n =
    if isPrime n then Some(n, n + 2) else nextPrime(n + 2)
and isPrime n =
    if n >= 2 then
        primes 
        |> Seq.tryFind (fun x -> n % x = 0 || x * x > n)
        |> fun x -> x.Value * x.Value > n
    else false

let isTruncatableL n =
    [let ns = string n
    for i = 0 to (String.length ns) - 1 do
        yield Convert.ToInt32(ns.Substring(i))] |> List.forall isPrime

let isTruncatableR n =
    [let ns = string n
    for i = (String.length ns) downto 1 do
        yield Convert.ToInt32(ns.Substring(0,i))] |> List.forall isPrime
        
let isTruncatable n = n > 7 && isTruncatableL n && isTruncatableR n

let problem037 () =
    primes
    |> Seq.filter isTruncatable |> (Seq.take 11 >> Seq.sum)
Advertisements

From → Project Euler

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: