Wagstaff primes: Difference between revisions

Content added Content deleted
(→‎OCaml: add)
(→‎OCaml: much faster without prime generator)
Line 307: Line 307:


=={{header|OCaml}}==
=={{header|OCaml}}==
Using the function <code>seq_primes</code> from [[Extensible prime generator#OCaml]]:
<syntaxhighlight lang="ocaml">let is_prime n =
<syntaxhighlight lang="ocaml">let is_prime n =
let not_divisible x = n mod x <> 0 in
let rec test x =
seq_primes |> Seq.take_while (fun x -> x * x <= n) |> Seq.for_all not_divisible
let q = n / x in x > q || x * q <> n && n mod (x + 2) <> 0 && test (x + 6)
in if n < 5 then n lor 1 = 3 else n land 1 <> 0 && n mod 3 <> 0 && test 5


let wagstaff n =
let is_wagstaff n =
let w = succ (1 lsl n) / 3 in
let w = succ (1 lsl n) / 3 in
if n <> 2 && is_prime w then Some (n, w) else None
if is_prime n && is_prime w then Some (n, w) else None


let () =
let () =
let show (p, w) = Printf.printf "%u -> %u%!\n" p w in
let show (p, w) = Printf.printf "%u -> %u%!\n" p w in
seq_primes |> Seq.filter_map wagstaff |> Seq.take 11 |> Seq.iter show</syntaxhighlight>
Seq.(ints 3 |> filter_map is_wagstaff |> take 11 |> iter show)</syntaxhighlight>
...checking for primality in a safe way. So, even when compiled with ''ocamlopt'', it takes more than three minutes to finish with the 11th.
{{out}}
{{out}}
<pre>
<pre>