Extreme primes: Difference between revisions

Content added Content deleted
m (→‎Embedded (GMP): Minor change.)
(Added Go)
Line 117: Line 117:
{{out}}
{{out}}
<pre>Similar to Ring entry.</pre>
<pre>Similar to Ring entry.</pre>

=={{header|Go}}==
{{trans|Wren}}
{{libheader|GMP(Go wrapper)}}
{{libheader|Go-rcu}}
Based on Wren's GMP version but about 4 times slower as our GMP wrapper doesn't expose the ''Mpz_nextprime'' function. We're therefore using our own very simple version instead which is much slower.
<syntaxhighlight lang="go">package main

import (
"fmt"
big "github.com/ncw/gmp"
"rcu"
)

func commatizeU64(n uint64) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}

func nextPrime(n *big.Int) *big.Int {
m := new(big.Int).Set(n)
z := new(big.Int)
zero := new(big.Int)
one := big.NewInt(1)
two := big.NewInt(2)
if z.Rem(m, two).Cmp(zero) == 0 {
m.Add(m, one)
} else {
m.Add(m, two)
}
for {
if m.ProbablyPrime(0) {
return m
}
m.Add(m, two)
}
}

func main() {
extremes := []int{2}
sum := big.NewInt(2)
count := 1
p := big.NewInt(3)
for {
sum.Add(sum, p)
if sum.ProbablyPrime(0) {
count++
if count <= 30 {
extremes = append(extremes, int(sum.Uint64()))
}
if count == 30 {
fmt.Println("The first 30 extreme primes are:")
rcu.PrintTable(extremes, 6, 7, true)
fmt.Println()
} else if count%1000 == 0 {
m := count / 1000
if m < 6 || m == 30 || m == 40 || m == 50 {
scount := rcu.Commatize(count)
ssum := commatizeU64(sum.Uint64())
sp := commatizeU64(p.Uint64())
fmt.Printf("The %6sth extreme prime is: %18s for p <= %10s\n", scount, ssum, sp)
if m == 50 {
return
}
}
}
}
p.Set(nextPrime(p))
}
}</syntaxhighlight>

{{out}}
<pre>
Identical to Wren output.
</pre>


=={{header|J}}==
=={{header|J}}==