Twin primes: Difference between revisions
m
→{{header|Wren}}: Minor tidy
(Added XPL0 example.) |
m (→{{header|Wren}}: Minor tidy) |
||
(14 intermediate revisions by 9 users not shown) | |||
Line 39:
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
Simplifies array bound checking by using the equivalent definition of twin primes: p and p - 2.
<
# count twin primes (where p and p - 2 are prime) #
PR heap=128M PR # set heap memory size for Algol 68G #
Line 64:
FOR p FROM 3 BY 2 TO max number - 1 DO IF primes[ p ] AND primes[ p - 2 ] THEN twin count +:= 1 FI OD;
print( ( "twin prime pairs below ", whole( max number, 0 ), ": ", whole( twin count, 0 ), newline ) )
END</
{{out}}
<pre>
Line 96:
=={{header|Arturo}}==
<
count: 0
j: 0
Line 117:
print ["From 2 to" ToNum ": there are" x "pairs of twin primes"]
ToNum: ToNum * 10
]</
{{out}}
Line 128:
From 2 to 1000000 : there are 8169 pairs of twin primes</pre>
=={{header|Applesoft BASIC}}==
<syntaxhighlight lang="gwbasic"> 0 INPUT "SEARCH SIZE: ";S: FOR N = 1 TO S - 3 STEP 2:P = N: GOSUB 3: IF F THEN P = N + 2: GOSUB 3:C = C + F
1 J = J + (N > 5): IF J = 3 THEN N = N + 4:J = 0
2 NEXT N: PRINT C" TWIN PRIME PAIRS.": END
3 F = 0: IF P < 2 THEN RETURN
4 F = P = 2: IF F THEN RETURN
5 F = P - INT (P / 2) * 2: IF NOT F THEN RETURN
6 FOR B = 3 TO SQR (P) STEP 2: IF B > = P THEN NEXT B
7 IF B > = P THEN RETURN
8 F = 0: FOR I = B TO SQR (P) STEP 2: IF P - INT (P / I) * I = 0 THEN RETURN
9 NEXT I:F = 1: RETURN</syntaxhighlight>
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f TWIN_PRIMES.AWK
BEGIN {
Line 163 ⟶ 174:
return(1)
}
</syntaxhighlight>
{{out}}
<pre>
Line 177 ⟶ 188:
=={{header|BASIC256}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="basic256">
function isPrime(v)
if v < 2 then return False
Line 209 ⟶ 220:
next i
end
</syntaxhighlight>
{{out}}
<pre>
Line 217 ⟶ 228:
=={{header|C}}==
<
#include <stdint.h>
#include <stdio.h>
Line 274 ⟶ 285:
test(100000000);
return 0;
}</
{{out}}
<pre>Number of twin prime pairs less than 10 is 2
Line 291 ⟶ 302:
(The module Math::Primesieve, which is used by the Raku example on this page, is implemented
on top of this library.)
<
#include <iostream>
#include <string>
Line 321 ⟶ 332:
}
return 0;
}</
{{out}}
Line 336 ⟶ 347:
Number of twin prime pairs less than 10,000,000,000 is 27,412,679
Number of twin prime pairs less than 100,000,000,000 is 224,376,048
</pre>
===Without external libraries===
<syntaxhighlight lang="c++">
#include <bitset>
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <vector>
const uint32_t limit = 1'000'000'000;
std::bitset<limit + 1> primes;
void sieve_primes(uint32_t limit) {
primes.set();
primes.reset(0); primes.reset(1);
for ( uint32_t p = 2; p * p <= limit; ++p ) {
if ( primes.test(p) ) {
for ( uint32_t i = p * p; i <= limit; i += p ) {
primes.reset(i);
}
}
}
}
int main() {
sieve_primes(limit);
uint32_t target = 10;
uint32_t count = 0;
bool last = false;
bool first = true;
for ( uint32_t index = 5; index <= limit; index += 2 ) {
last = first;
first = primes[index];
if ( last && first ) {
count += 1;
}
if ( index + 1 == target ) {
std::cout << std::setw(8) << count << " twin primes below " << index + 1 << std::endl;
target *= 10;
}
}
}
</syntaxhighlight>
{{ out }}
<pre>
2 twin primes below 10
8 twin primes below 100
35 twin primes below 1000
205 twin primes below 10000
1224 twin primes below 100000
8169 twin primes below 1000000
58980 twin primes below 10000000
440312 twin primes below 100000000
3424506 twin primes below 1000000000
</pre>
=={{header|C sharp}}==
===Conventional===
<
class Program {
Line 397 ⟶ 466:
Console.Write("{0} sec", sw.Elapsed.TotalSeconds);
}
}</
{{out|Output @ Tio.run}}
<pre> 2 twin primes below 10
Line 413 ⟶ 482:
{{works with|C sharp|8}}
Runs in about 18 seconds.
<
using System.Linq;
using System.Collections;
Line 475 ⟶ 544:
}
}
}</
{{out}}
<pre style="height:30ex;overflow:scroll">
Line 491 ⟶ 560:
{{libheader| System.SysUtils}}
{{Trans|Wren}}
<syntaxhighlight lang="delphi">
program Primes;
Line 612 ⟶ 681:
end.
</syntaxhighlight>
{{out}}
Line 626 ⟶ 695:
Under 1,000,000,000 there are 3,424,506 pairs of twin primes.
</pre>
=={{header|EasyLang}}==
{{trans|AWK}}
<syntaxhighlight lang=easylang>
fastfunc isprim num .
if num mod 2 = 0 and num > 2
return 0
.
i = 3
while i <= sqrt num
if num mod i = 0
return 0
.
i += 2
.
return 1
.
func count limit .
p2 = 1
p3 = 1
for i = 5 to limit
p3 = p2
p2 = p1
p1 = isprim i
if p3 = 1 and p1 = 1
cnt += 1
.
.
return cnt
.
n = 1
for i = 1 to 6
n *= 10
print "twin prime pairs < " & n & " : " & count n
.
</syntaxhighlight>
=={{header|F Sharp|F#}}==
This task uses [http://www.rosettacode.org/wiki/Extensible_prime_generator#The_function Extensible Prime Generator (F#)]
<
printfn "twin primes below 100000: %d" (primes64()|>Seq.takeWhile(fun n->n<=100000L)|>Seq.pairwise|>Seq.filter(fun(n,g)->g=n+2L)|>Seq.length)
printfn "twin primes below 1000000: %d" (primes64()|>Seq.takeWhile(fun n->n<=1000000L)|>Seq.pairwise|>Seq.filter(fun(n,g)->g=n+2L)|>Seq.length)
Line 637 ⟶ 742:
printfn "twin primes below 10000000000: %d" (primes64()|>Seq.takeWhile(fun n->n<=10000000000L)|>Seq.pairwise|>Seq.filter(fun(n,g)->g=n+2L)|>Seq.length)
printfn "twin primes below 100000000000: %d" (primes64()|>Seq.takeWhile(fun n->n<=100000000000L)|>Seq.pairwise|>Seq.filter(fun(n,g)->g=n+2L)|>Seq.length)
</syntaxhighlight>
{{out}}
<pre>
Line 664 ⟶ 769:
=={{header|Factor}}==
{{works with|Factor|0.99 2020-07-03}}
<
sequences tools.memory.private ;
Line 672 ⟶ 777:
"Search size: " write flush readln string>number
twin-pair-count commas write " twin prime pairs." print</
{{out}}
<pre>
Line 690 ⟶ 795:
=={{header|FreeBASIC}}==
{{trans|AWK}}
<
Function isPrime(Byval ValorEval As Integer) As Boolean
If ValorEval <=1 Then Return False
Line 717 ⟶ 822:
Print !"\n--- terminado, pulsa RETURN---"
Sleep
</syntaxhighlight>
{{out}}
<pre>
Line 726 ⟶ 831:
pares de primos gemelos por debajo de < 100000 : 1224
pares de primos gemelos por debajo de < 1000000 : 8169
</pre>
=={{header|Frink}}==
<syntaxhighlight lang="frink">upper = eval[input["Enter upper bound:"]]
countTwins[upper]
countTwins[100000]
countTwins[10000000]
countTwins[1000000000]
countTwins[upper] :=
{
count = 0
for n = primes[2, upper-2]
if isPrime[n+2]
count = count + 1
println["$count twin primes under $upper"]
}</syntaxhighlight>
{{out}}
<pre>
35 twin primes under 1000
1224 twin primes under 100000
58980 twin primes under 10000000
3424506 twin primes under 1000000000
</pre>
=={{header|Go}}==
{{trans|Wren}}
<
import "fmt"
Line 790 ⟶ 919:
limit *= 10
}
}</
{{out}}
Line 808 ⟶ 937:
===Alternative using primegen package===
See [[Extensible prime generator#Go]].
<
import (
Line 836 ⟶ 965:
previous = prime
}
}</
{{out}}
Line 854 ⟶ 983:
=={{header|Java}}==
BigInteger Implementation:
<syntaxhighlight lang="java">
import java.math.BigInteger;
import java.util.Scanner;
Line 881 ⟶ 1,010:
}
}
</syntaxhighlight>
{{out}}
<pre>
Line 893 ⟶ 1,022:
> 1000
> 35 twin prime pairs.
</pre>
===Extended Task===
<syntaxhighlight lang="java">
import java.util.BitSet;
public final class TwinPrimes {
public static void main(String[] args) {
final int limit = 1_000_000_000;
sievePrimes(limit);
int target = 10;
int count = 0;
boolean last = false;
boolean first = true;
for ( int index = 5; index <= limit; index += 2 ) {
last = first;
first = primes.get(index);
if ( last && first ) {
count += 1;
}
if ( index + 1 == target ) {
System.out.println(String.format("%8d%s%d", count, " twin primes below ", index + 1));
target *= 10;
}
}
}
private static void sievePrimes(int aLimit) {
primes = new BitSet(aLimit + 1);
primes.set(2, aLimit + 1);
for ( int i = 2; i <= Math.sqrt(aLimit); i = primes.nextSetBit(i + 1) ) {
for ( int j = i * i; j <= aLimit; j += i ) {
primes.clear(j);
}
}
}
private static BitSet primes;
}
</syntaxhighlight>
{{ out }}
<pre>
2 twin primes below 10
8 twin primes below 100
35 twin primes below 1000
205 twin primes below 10000
1224 twin primes below 100000
8169 twin primes below 1000000
58980 twin primes below 10000000
440312 twin primes below 100000000
3424506 twin primes below 1000000000
</pre>
=={{header|J}}==
<
NB. i.&.(p:inv) generate a list of primes below the given limit
NB.
NB. _2 +/@:= compare these differences to -2, and
NB. sum up the resulting boolean list (get the number of twin pairs)</syntaxhighlight>
{{out}}
<pre> tp
2 8 35 205 1224 8169 58980
NB. test larger limits, and get their time/space usage
tp
440312
timespacex 'tp
0.657576 2.01377e8
tp 1e9
3424506
timespacex 'tp 1e9'
8.59713 1.61071e9
</pre>
=={{header|jq}}==
'''Slightly modified from the [[#C|C]] entry'''
<
. as $n
| if ($n % 3 == 0) then $n == 3
Line 947 ⟶ 1,128:
| .count;
pow(10; range(1;8)) | "Number of twin primes less than \(.) is \(twin_primes(.))."</
{{out}}
<pre>
Line 960 ⟶ 1,141:
=={{header|Julia}}==
<
function counttwinprimepairsbetween(n1, n2)
Line 979 ⟶ 1,160:
lpad(format(paircount, commas=true), 8), " pairs of twin primes.")
end
</
<pre>
Under 100 there are 8 pairs of twin primes.
Line 1,000 ⟶ 1,181:
prime pair as a difference tuple of (2,), and a prime quadruplet such as [11, 13, 17, 19] as the
tuple starting with 11 of type (2, 6, 8).
<
const PMAX = 1_000_000_000
Line 1,019 ⟶ 1,200:
println("Count of a form of prime octets from 1 to 1 million: ",
format(countprimetuples((2, 6, 12, 14, 20, 24, 26), 1000000), commas=true))
</
<pre>
Count of prime pairs from 1 to 1 billion: 3,424,506
Line 1,028 ⟶ 1,209:
=={{header|Kotlin}}==
{{trans|Java}}
<
import java.util.*
Line 1,060 ⟶ 1,241:
}
return true
}</
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
TwinPrimeCount[mx_] := Module[{pmax, min, max, total},
pmax = PrimePi[mx];
Line 1,078 ⟶ 1,259:
total
]
Do[Print[{10^i, TwinPrimeCount[10^i]}], {i, 9}]</
{{out}}
<pre>{10,2}
Line 1,089 ⟶ 1,270:
{100000000,440312}
{1000000000,3424506}</pre>
=={{header|Maxima}}==
Using built-in predicate function primep to detect primes and the fact that all but the first pair are of the form [6n-1,6n+1].
<syntaxhighlight lang="maxima">
/* Function to count the number of pairs below n */
twin_primes_under_n(n):=block(
L:makelist([6*i-1,6*i+1],i,1,floor(n/6)),
caching:length(L),
L1:[],
for i from 1 thru caching do if map(primep,L[i])=[true,true] then push(L[i],L1),
append([[3,5]],reverse(L1)),
length(%%));
/* Test cases */
twin_primes_under_n(10);
twin_primes_under_n(100);
twin_primes_under_n(1000);
twin_primes_under_n(10000);
twin_primes_under_n(100000);
</syntaxhighlight>
{{out}}
<pre>
2
8
35
205
1224
</pre>
=={{header|Nim}}==
Line 1,095 ⟶ 1,304:
As, except for the pair (3, 5), all twins pairs are composed of a number congruent to 2 modulo 3 and a number congruent to 1 modulo 3, we can save some time by using a step of 6. Unfortunately, this is the filling of the sieve which is the most time consuming, so the gain is not very important (on our computer, half a second on a total time of 8.3 s).
<
const N = 1_000_000_000
Line 1,124 ⟶ 1,333:
if lim > N: break
composite.findTwins()</
{{out}}
Line 1,138 ⟶ 1,347:
=={{header|Perl}}==
<
use warnings;
Line 1,145 ⟶ 1,354:
sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }
printf "Twin prime pairs less than %14s: %s\n", comma(10**$_), comma count_twins(1, 10**$_) for 1..10;</
{{out}}
<pre>Twin prime pairs less than 10: 2
Line 1,163 ⟶ 1,372:
The time complexity here is all about building a table of primes. It turns out that using the builtin get_prime() is actually faster
than using an explicit sieve (as per Delphi/Go/Wren) due to retaining all the intermediate 0s, not that I particularly expect this to win any performance trophies.
<!--
<syntaxhighlight lang="phix">
with javascript_semantics
atom t0 = time()
function twin_primes(integer maxp, bool both=true)
integer n = 0, -- result
pn = 2, -- next prime index
p, -- a prime, <= maxp
prev_p = 2
while true do
p = get_prime(pn)
if both and p>=maxp then exit end if
n += (prev_p = p-2)
if (not both) and p>=maxp then exit end if
prev_p = p
pn += 1
end while
return n
end function
integer mp = 6 -- prompt_number("Enter limit:")
printf(1,"Twin prime pairs less than %,d: %,d\n",{mp,twin_primes(mp)})
printf(1,"Twin prime pairs less than %,d: %,d\n",{mp,twin_primes(mp,false)})
for p=1 to 9 do
integer p10 = power(10,p)
printf(1,"Twin prime pairs less than %,d: %,d\n",{p10,twin_primes(p10)})
end for
?elapsed(time()-t0)
</syntaxhighlight>
{{out}}
<pre>
Line 1,205 ⟶ 1,415:
"16.2s"
</pre>
=== using primesieve ===
Windows 64-bit only, unless you can find/make a suitable dll/so.<br>
Note that unlike the above this version of twin_primes() carries on from where it left off.
<syntaxhighlight lang="phix">
requires(WINDOWS)
requires(64,true)
include builtins/primesieve.e
atom t0 = time()
integer n = 0, p = 2, prev_p = 2
function twin_primes(integer maxp, bool both=true)
while true do
if both and p>=maxp then exit end if
n += (prev_p = p-2)
if (not both) and p>=maxp then exit end if
prev_p = p
p = primesieve_next_prime()
end while
return n
end function
for i=1 to 11 do
integer p10 = power(10,i)
printf(1,"Twin prime pairs less than %,d: %,d\n",{p10,twin_primes(p10)})
end for
?elapsed(time()-t0)
</syntaxhighlight>
{{out}}
Same as above, which it completes in 7.2s (and 1e10 in 1 min 6s), less the 6's and plus two more lines:
<pre>
Twin prime pairs less than 10: 2
Twin prime pairs less than 100: 8
Twin prime pairs less than 1,000: 35
Twin prime pairs less than 10,000: 205
Twin prime pairs less than 100,000: 1,224
Twin prime pairs less than 1,000,000: 8,169
Twin prime pairs less than 10,000,000: 58,980
Twin prime pairs less than 100,000,000: 440,312
Twin prime pairs less than 1,000,000,000: 3,424,506
Twin prime pairs less than 10,000,000,000: 27,412,679
Twin prime pairs less than 100,000,000,000: 224,376,048
"10 minutes and 25s"
</pre>
=={{header|PureBasic}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="purebasic">
Procedure isPrime(v.i)
If v <= 1 : ProcedureReturn #False
Line 1,254 ⟶ 1,504:
CloseConsole()
End
</syntaxhighlight>
{{out}}
<pre>
Line 1,263 ⟶ 1,513:
=={{header|Python}}==
<
Line 1,300 ⟶ 1,550:
test(1000000)
test(10000000)
test(100000000)</
{{out}}
<pre>Number of twin prime pairs less than 10 is 2
Line 1,316 ⟶ 1,566:
<code>primes</code> and <code>eratosthenes</code> are defined at [[Sieve of Eratosthenes#Quackery]].
<
[ eratosthenes
0 1 primes share ]
Line 1,332 ⟶ 1,582:
10 i^ 1+ ** dup echo
say " is "
twinprimes echo say "." cr ]</
{{out}}
Line 1,346 ⟶ 1,596:
{{works with|Rakudo|2020.07}}
<syntaxhighlight lang="raku"
use Math::Primesieve;
Line 1,352 ⟶ 1,602:
my $p = Math::Primesieve.new;
printf "Twin prime pairs less than %
say (now - INIT now).round(.01) ~ ' seconds';</syntaxhighlight>
{{out}}
<pre>Twin prime pairs less than 10: 2
Twin prime pairs less than 100: 8
Twin prime pairs less than 1,000: 35
Twin prime pairs less than 10,000: 205
Twin prime pairs less than 100,000: 1,224
Twin prime pairs less than 1,000,000: 8,169
Twin prime pairs less than 10,000,000: 58,980
Twin prime pairs less than 100,000,000: 440,312
Twin prime pairs less than 1,000,000,000: 3,424,506
Twin prime pairs less than 10,000,000,000: 27,412,679
Twin prime pairs less than 100,000,000,000: 224,376,048
Twin prime pairs less than 1,000,000,000,000: 1,870,585,220
6.89 seconds</pre>
=={{header|REXX}}==
=== straight-forward prime generator ===
The '''genP''' function could be optimized for higher specifications of the limit(s).
<
parse arg $ . /*get optional number of primes to find*/
if $='' | $="," then $= 10 100 1000 10000 100000 1000000 10000000 /*No $? Use default.*/
Line 1,393 ⟶ 1,647:
prev= @.#; #= #+1; sq.#= j*j; @.#= j /*save prev. P; bump # primes; assign P*/
if j-2==prev then tp= tp + 1 /*This & previous prime twins? Bump TP.*/
end /*j*/; return tp</
{{out|output|text= when using the default inputs:}}
<pre>
Line 1,410 ⟶ 1,664:
This version won't return a correct value (for the number of twin pairs) for a limit < 73 (because of the manner in
<br>which low primes are generated from a list), however, the primes are returned from the function.
<
parse arg $ . /*get optional number of primes to find*/
if $='' | $="," then $= 100 1000 10000 100000 1000000 10000000 /*No $? Use default.*/
Line 1,442 ⟶ 1,696:
prev= @.#; #= #+1; sq.#= j*j; @.#= j /*save prev. P; bump # primes; assign P*/
if j-2==prev then tp= tp + 1 /*This & previous prime twins? Bump TP.*/
end /*j*/; return tp</
=={{header|Ring}}==
<
load "stdlib.ring"
Line 1,481 ⟶ 1,735:
see "twin prime pairs below " + pow(10,n) + ": " + numTwin[n] + nl + nl
next
</syntaxhighlight>
Output:
<pre>
Line 1,504 ⟶ 1,758:
Maximum: 10000000
twin prime pairs below 10000000: 58980
</pre>
=={{header|RPL}}==
{{works with|HP|49}}
« → m
« 0 2
'''WHILE''' DUP m < '''REPEAT'''
DUP NEXTPRIME DUP ROT - 2 == ROT + SWAP
'''END''' DROP
» » ‘<span style="color:blue">TWINP</span>’ STO
100000 <span style="color:blue">TWINP</span>
{{out}}
<pre>
1: 1224
</pre>
=={{header|Ruby}}==
<
(1..8).each do |n|
Line 1,513 ⟶ 1,782:
puts "Twin primes below 10**#{n}: #{count}"
end
</syntaxhighlight>
{{out}}
<pre>Twin primes below 10**1: 2
Line 1,528 ⟶ 1,797:
Limits can be specified on the command line, otherwise the twin prime counts for powers
of ten from 1 to 10 are shown.
<
// primal = "0.3"
// num-format = "0.4"
Line 1,588 ⟶ 1,857:
twin_prime_count_for_powers_of_ten(10);
}
}</
{{out}}
Line 1,605 ⟶ 1,874:
=={{header|Sidef}}==
<
var count = 0
var p1 = 2
Line 1,620 ⟶ 1,889:
var count = twin_primes_count(10**n)
say "There are #{count} twin primes <= 10^#{n}"
}</
{{out}}
<pre>
Line 1,638 ⟶ 1,907:
{{works with|Visual Basic|5}}
{{works with|Visual Basic|6}}
<
Dim i As Long
If x Mod 2 = 0 Then
Line 1,673 ⟶ 1,942:
Test 1000000
Test 10000000
End Sub</
{{out}}
<pre>Twin prime pairs below 10: 2
Line 1,686 ⟶ 1,955:
{{libheader|Wren-math}}
{{libheader|Wren-fmt}}
<
import "./fmt" for Fmt
var c = Int.primeSieve(1e8-1, false)
Line 1,702 ⟶ 1,971:
start = limit + 1
limit = limit * 10
}</
{{out}}
Line 1,717 ⟶ 1,986:
=={{header|XPL0}}==
100 million takes 150 seconds on Pi4.
<
int N, I;
[if N <= 2 then return N = 2;
Line 1,745 ⟶ 2,014:
IntOut(0, Twins(10_000_000)); CrLf(0);
IntOut(0, Twins(100_000_000)); CrLf(0);
]</
{{out}}
Line 1,756 ⟶ 2,025:
=={{header|Yabasic}}==
{{trans|FreeBASIC}}
<
sub isPrime(v)
if v < 2 then return False : fi
Line 1,785 ⟶ 2,054:
next i
end
</syntaxhighlight>
{{out}}
<pre>
|