Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can refer my <a href="http://fsharp-euler.wikispaces.com/euler+007" rel="nofollow noreferrer">F# for Project Euler Wiki</a>:</p> <p>I got this first version:</p> <pre><code>let isPrime n = if n=1 then false else let m = int(sqrt (float(n))) let mutable p = true for i in 2..m do if n%i =0 then p &lt;- false // ~~ I want to break here! p let rec nextPrime n = if isPrime n then n else nextPrime (n+1) let problem7 = let mutable result = nextPrime 2 for i in 2..10001 do result &lt;- nextPrime (result+1) result </code></pre> <p>In this version, although looks nicer, but I still does not early break the loop when the number is not a prime. In Seq module, exist and forall methods support early stop:</p> <pre><code>let isPrime n = if n&lt;=1 then false else let m = int(sqrt (float(n))) {2..m} |&gt; Seq.exists (fun i-&gt;n%i=0) |&gt; not // or equivalently : // {2..m} |&gt; Seq.forall (fun i-&gt;n%i&lt;&gt;0) </code></pre> <p>Notice in this version of isPrime, the function is finally mathematically correct by checking numbers below 2.</p> <p>Or you can use a tail recursive function to do the while loop:</p> <pre><code>let isPrime n = let m = int(sqrt (float(n))) let rec loop i = if i&gt;m then true else if n%i = 0 then false else loop (i+1) loop 2 </code></pre> <p>A more functional version of problem7 is to use Seq.unfold to generate an infinite prime sequence and take nth element of this sequence:</p> <pre><code>let problem7b = let primes = 2 |&gt; Seq.unfold (fun p -&gt; let next = nextPrime (p+1) in Some( p, next ) ) Seq.nth 10000 primes </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload