I'm working on modernizing Rosetta Code's infrastructure. Starting with communications. Please accept this time-limited open invite to RC's Slack.. --Michael Mol (talk) 20:59, 30 May 2020 (UTC)

Neighbour primes

From Rosetta Code
Neighbour primes is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.
Task

Find and show primes p such that p*q+2 is prime, where q is next prime after p and p < 500

ALGOL W[edit]

begin % find some primes where ( p*q ) + 2 is also a prime ( where p and q are adjacent primes ) %
 % sets p( 1 :: n ) to a sieve of primes up to n %
procedure sieve ( logical array p( * ) ; integer value n ) ;
begin
p( 1 ) := false; p( 2 ) := true;
for i := 3 step 2 until n do p( i ) := true;
for i := 4 step 2 until n do p( i ) := false;
for i := 3 step 2 until truncate( sqrt( n ) ) do begin
integer ii; ii := i + i;
if p( i ) then for np := i * i step ii until n do p( np ) := false
end for_i ;
end sieve ;
integer MAX_NUMBER, MAX_PRIME;
MAX_NUMBER := 500;
MAX_PRIME  := MAX_NUMBER * MAX_NUMBER;
begin
logical array prime( 1 :: MAX_PRIME );
integer pCount, thisPrime, nextPrime;
 % sieve the primes to MAX_PRIME %
sieve( prime, MAX_PRIME );
 % find the neighbour primes %
pCount  := 0;
thisPrime := 2; % 2 is the lowest prime %
while thisPrime > 0 do begin
 % find the next prime after this one %
nextPrime := thisPrime + 1;
while nextPrime <= MAX_NUMBER and not prime( nextPrime ) do nextPrime := nextPrime + 1;
if nextPrime > MAX_NUMBER then thisPrime := 0
else begin
if prime( ( thisPrime * nextPrime ) + 2 ) then begin
 % have another neighbour prime %
writeon( i_w := 1, s_w := 0, " ", thisPrime );
pCount := pCount + 1
end if_prime__thisPrime_x_nextPrime_plus_2 ;
thisPrime := nextPrime
end if_nextPrime_gt_MAX_NUMBER__
end while_thisPrime_gt_0 ;
write( i_w := 1, s_w := 0, "Found ", pCount, " neighbour primes up to 500" )
end
end.
Output:
 3 5 7 13 19 67 149 179 229 239 241 269 277 307 313 397 401 419 439 487
Found 20 neighbour primes up to 500

AWK[edit]

 
# syntax: GAWK -f NEIGHBOUR_PRIMES.AWK
BEGIN {
print(" p q p*q+2")
print("---- ---- ------")
start = 1
stop = 499
for (p=start; p<=stop; p++) {
if (!is_prime(p)) { continue }
q = p + 1
while (!is_prime(q)) {
q++
}
if (!is_prime(p*q+2)) { continue }
printf("%4d %4d %6d\n",p,q,p*q+2)
count++
}
printf("Neighbour primes %d-%d: %d\n",start,stop,count)
exit(0)
}
function is_prime(x, i) {
if (x <= 1) {
return(0)
}
for (i=2; i<=int(sqrt(x)); i++) {
if (x % i == 0) {
return(0)
}
}
return(1)
}
 
Output:
   p    q  p*q+2
---- ---- ------
   3    5     17
   5    7     37
   7   11     79
  13   17    223
  19   23    439
  67   71   4759
 149  151  22501
 179  181  32401
 229  233  53359
 239  241  57601
 241  251  60493
 269  271  72901
 277  281  77839
 307  311  95479
 313  317  99223
 397  401 159199
 401  409 164011
 419  421 176401
 439  443 194479
 487  491 239119
Neighbour primes 1-499: 20

C#[edit]

How about some other offsets besides + 2 ?

using System; using System.Collections.Generic;
using System.Linq; using static System.Console; using System.Collections;
 
class Program {
static void Main(string[] args) {
WriteLine ("Multiply two consecutive prime numbers, add an even number," +
" see if the result is a prime number (up to a limit).");
int c, lim = 500; var pr = PG.Primes(lim * lim).ToList();
pr = pr.TakeWhile(x => x < lim).ToList();
var Lst = new[]{ Tuple.Create(2, 2), Tuple.Create(-20, 20) };
foreach (var pair in Lst) {
bool sho = pair.Item1 == pair.Item2;
for (int ofs = pair.Item1; ofs <= pair.Item2; ofs += ofs == -2 ? 4 : 2) {
c = 0; string s = ofs.ToString("+0;-#").Insert(1, " ");
for (int i = 0, j = 1, k; j < pr.Count; i = j++)
if (PG.isPr(k = pr[i] * pr[j] + ofs))
if (sho) WriteLine (" {0,3} * {1,3} {2} = {3,-6}",
pr[i], pr[j], s, k, c++);
else c++;
WriteLine("{0,2} found under {1} for \" {2} \"", c, lim, s);
} WriteLine (); } } }
 
class PG { static bool[] flags; public static bool isPr(int x) {
if (x < 2) return false; return !flags[x]; }
public static IEnumerable<int> Primes(int lim) {
flags = new bool[lim + 1]; int j = 3;
for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)
if (!flags[j]) { yield return j;
for (int k = sq, i=j<<1; k<=lim; k += i) flags[k] = true; }
for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }
Output:
Multiply two consecutive prime numbers, add an even number, see if the result is a prime number (up to a limit).
     3 *   5 + 2 = 17    
     5 *   7 + 2 = 37    
     7 *  11 + 2 = 79    
    13 *  17 + 2 = 223   
    19 *  23 + 2 = 439   
    67 *  71 + 2 = 4759  
   149 * 151 + 2 = 22501 
   179 * 181 + 2 = 32401 
   229 * 233 + 2 = 53359 
   239 * 241 + 2 = 57601 
   241 * 251 + 2 = 60493 
   269 * 271 + 2 = 72901 
   277 * 281 + 2 = 77839 
   307 * 311 + 2 = 95479 
   313 * 317 + 2 = 99223 
   397 * 401 + 2 = 159199
   401 * 409 + 2 = 164011
   419 * 421 + 2 = 176401
   439 * 443 + 2 = 194479
   487 * 491 + 2 = 239119
20 found under 500 for " + 2 "

 5 found under 500 for " - 20 "
26 found under 500 for " - 18 "
22 found under 500 for " - 16 "
10 found under 500 for " - 14 "
22 found under 500 for " - 12 "
21 found under 500 for " - 10 "
13 found under 500 for " - 8 "
32 found under 500 for " - 6 "
20 found under 500 for " - 4 "
 5 found under 500 for " - 2 "
20 found under 500 for " + 2 "
 9 found under 500 for " + 4 "
36 found under 500 for " + 6 "
18 found under 500 for " + 8 "
11 found under 500 for " + 10 "
27 found under 500 for " + 12 "
20 found under 500 for " + 14 "
 8 found under 500 for " + 16 "
17 found under 500 for " + 18 "
25 found under 500 for " + 20 "

F#[edit]

This task uses Extensible Prime Generator (F#)

 
// Nigel Galloway. April 13th., 2021
primes32()|>Seq.pairwise|>Seq.takeWhile(fun(n,_)->n<500)|>Seq.filter(fun(n,g)->isPrime(n*g+2))|>Seq.iter(fun(n,g)->printfn "%d*%d=%d" n g (n*g+2))
 
Output:
3*5=17
5*7=37
7*11=79
13*17=223
19*23=439
67*71=4759
149*151=22501
179*181=32401
229*233=53359
239*241=57601
241*251=60493
269*271=72901
277*281=77839
307*311=95479
313*317=99223
397*401=159199
401*409=164011
419*421=176401
439*443=194479
487*491=239119
Real: 00:00:00.029

Factor[edit]

Works with: Factor version 0.99 2021-02-05
USING: formatting io kernel math math.primes ;
 
"p q p*q+2" print
2 3
[ over 500 < ] [
2dup * 2 + dup prime?
[ 3dup "%-4d %-4d %-6d\n" printf ] when
drop nip dup next-prime
] while 2drop
Output:
p    q    p*q+2
3    5    17    
5    7    37    
7    11   79    
13   17   223   
19   23   439   
67   71   4759  
149  151  22501 
179  181  32401 
229  233  53359 
239  241  57601 
241  251  60493 
269  271  72901 
277  281  77839 
307  311  95479 
313  317  99223 
397  401  159199
401  409  164011
419  421  176401
439  443  194479
487  491  239119

Fermat[edit]

Translation of: PARI/GP
for i = 1 to 95 do if Isprime(2+Prime(i)*Prime(i+1)) then !!Prime(i) fi od

FreeBASIC[edit]

#include "isprime.bas"
 
dim as uinteger q
 
print "p q pq+2"
print "--------------------------------"
for p as uinteger = 2 to 499
if not isprime(p) then continue for
q = p + 1
while not isprime(q)
q+=1
wend
if not isprime( 2 + p*q ) then continue for
print p,q,2+p*q
next p
Output:
p             q             pq+2
--------------------------------
3             5             17
5             7             37
7             11            79
13            17            223
19            23            439
67            71            4759
149           151           22501
179           181           32401
229           233           53359
239           241           57601
241           251           60493
269           271           72901
277           281           77839
307           311           95479
313           317           99223
397           401           159199
401           409           164011
419           421           176401
439           443           194479
487           491           239119

Go[edit]

Translation of: Wren
Library: Go-rcu
package main
 
import (
"fmt"
"rcu"
)
 
func main() {
primes := rcu.Primes(504)
var nprimes []int
fmt.Println("Neighbour primes < 500:")
for i := 0; i < len(primes)-1; i++ {
p := primes[i]*primes[i+1] + 2
if rcu.IsPrime(p) {
nprimes = append(nprimes, primes[i])
}
}
rcu.PrintTable(nprimes, 10, 3, false)
fmt.Println("\nFound", len(nprimes), "such primes.")
}
Output:
Neighbour primes < 500:
  3   5   7  13  19  67 149 179 229 239 
241 269 277 307 313 397 401 419 439 487 

Found 20 such primes.

Julia[edit]

using Primes
 
isneiprime(known) = isprime(known) && isprime(known * nextprime(known + 1) + 2)
println(filter(isneiprime, primes(500)))
 
Output:
[3, 5, 7, 13, 19, 67, 149, 179, 229, 239, 241, 269, 277, 307, 313, 397, 401, 419, 439, 487]

PARI/GP[edit]

Cheats a little in the sense that it requires knowing the 95th prime is 499 beforehand.

for(i=1, 95, if(isprime(2+prime(i)*prime(i+1)),print(prime(i))))

Perl[edit]

Library: ntheory
use strict;
use warnings;
use ntheory <next_prime is_prime>;
 
my $p = 2;
do {
my $q = next_prime($p);
printf "%3d%5d%8d\n", $p, $q, $p*$q+2 if is_prime $p*$q+2;
$p = $q;
} until $p >= 500;
Output:
  3    5      17
  5    7      37
  7   11      79
 13   17     223
 19   23     439
 67   71    4759
149  151   22501
179  181   32401
229  233   53359
239  241   57601
241  251   60493
269  271   72901
277  281   77839
307  311   95479
313  317   99223
397  401  159199
401  409  164011
419  421  176401
439  443  194479
487  491  239119

Phix[edit]

function np(integer p) return is_prime(get_prime(p)*get_prime(p+1)+2) end function
constant N = length(get_primes_le(500))
sequence res = apply(apply(filter(tagset(N),np),get_prime),sprint)
printf(1,"Found %d such primes: %s\n",{length(res),join(shorten(res,"",5),", ")})
Output:
Found 20 such primes: 3, 5, 7, 13, 19, ..., 397, 401, 419, 439, 487

Raku[edit]

my @primes = grep &is-prime, ^Inf;
my $last_p = @primes.first: :k, * >= 500;
my $last_q = $last_p + 1;
 
my @cousins = @primes.head( $last_q )
.rotor( 2 => -1 )
.map(-> (\p, \q) { p, q, p*q+2 } )
.grep( *.[2].is-prime );
 
say .fmt('%6d') for @cousins;
Output:
     3      5     17
     5      7     37
     7     11     79
    13     17    223
    19     23    439
    67     71   4759
   149    151  22501
   179    181  32401
   229    233  53359
   239    241  57601
   241    251  60493
   269    271  72901
   277    281  77839
   307    311  95479
   313    317  99223
   397    401 159199
   401    409 164011
   419    421 176401
   439    443 194479
   487    491 239119

REXX[edit]

Neighbor primes can also be spelled neighbour primes.

/*REXX program finds neighbor primes: P, Q, P*Q+2 are primes, and  P < some specified N.*/
parse arg hi cols . /*obtain optional argument from the CL.*/
if hi=='' | hi=="," then hi= 500 /*Not specified? Then use the default.*/
if cols=='' | cols=="," then cols= 10 /* " " " " " " */
call genP hi+50 /*build semaphore array for low primes.*/
do p=1 while @.p<hi
end /*p*/; lim= p-1; q= p+1 /*set LIM to prime for P; calc. 2nd HI.*/
call genP @.p * @.q + 2 /*build semaphore array for high primes*/
w= 10 /*width of a number in any column. */
@neig= ' neighbor primes: p, q, p*q+2 are primes, and p < ' commas(hi)
if cols>0 then say ' index │'center(@neig, 1 + cols*(w+1) )
if cols>0 then say '───────┼'center("" , 1 + cols*(w+1), '─')
Nprimes= 0; idx= 1 /*initialize # neighbor primes & index.*/
$= /*a list of neighbor primes (so far).*/
do j=1 to lim; jp= j+1; q= @.jp /*look for neighbor primes within range*/
x= @.j * q + 2; if \!.x then iterate /*is X also a prime? No, then skip it.*/
Nprimes= Nprimes + 1 /*bump the number of neighbor primes. */
if cols==0 then iterate /*Build the list (to be shown later)? */
$= $ right( commas(@.j), w) /*add neighbor prime ──► the $ list. */
if Nprimes//cols\==0 then iterate /*have we populated a line of output? */
say center(idx, 7)'│' substr($, 2); $= /*display what we have so far (cols). */
idx= idx + cols /*bump the index count for the output*/
end /*j*/
 
if $\=='' then say center(idx, 7)"│" substr($, 2) /*possible display residual output.*/
if cols>0 then say '───────┴'center("" , 1 + cols*(w+1), '─')
say
say 'Found ' commas(Nprimes) @neig
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ?
/*──────────────────────────────────────────────────────────────────────────────────────*/
genP: !.= 0; parse arg limit /*placeholders for primes (semaphores).*/
@.1=2; @.2=3; @.3=5; @.4=7; @.5=11 /*define some low primes. */
 !.2=1;  !.3=1;  !.5=1;  !.7=1;  !.11=1 /* " " " " flags. */
#=5; s.#= @.# **2 /*number of primes so far; prime². */
/* [↓] generate more primes ≤ high.*/
do [email protected].#+2 by 2 to limit /*find odd primes from here on. */
parse var j '' -1 _; if _==5 then iterate /*J divisible by 5? (right dig)*/
if j// 3==0 then iterate /*" " " 3? */
if j// 7==0 then iterate /*" " " 7? */
/* [↑] the above 3 lines saves time.*/
do k=5 while s.k<=j /* [↓] divide by the known odd primes.*/
if j // @.k == 0 then iterate j /*Is J ÷ X? Then not prime. ___ */
end /*k*/ /* [↑] only process numbers ≤ √ J */
#= #+1; @.#= j; s.#= j*j;  !.j= 1 /*bump # of Ps; assign next P; P²; P# */
end /*j*/; return
output   when using the default inputs:
 index │                           neighbor primes:  p, q, p*q+2  are primes,  and p  <  500
───────┼───────────────────────────────────────────────────────────────────────────────────────────────────────────────
   1   │          3          5          7         13         19         67        149        179        229        239
  11   │        241        269        277        307        313        397        401        419        439        487
───────┴───────────────────────────────────────────────────────────────────────────────────────────────────────────────

Found  20  neighbor primes:  p, q, p*q+2  are primes,  and p  <  500

Ring[edit]

 
load "stdlib.ring"
see "working..." + nl
see "Neighbour primes are:" + nl
see "p q p*q+2" + nl
 
row = 0
num = 0
pr = 0
limit = 100
Primes = []
 
while true
pr = pr + 1
if isprime(pr)
add(Primes,pr)
num = num + 1
if num = limit
exit
ok
ok
end
 
for n = 1 to limit-1
prim = Primes[n]*Primes[n+1]+2
if isprime(prim)
row = row + 1
see "" + Primes[n] + " " + Primes[n+1] + " " + prim + nl
ok
next
 
see "Found " + row + " neighbour primes" + nl
see "done..." + nl
 
Output:
working...
Neighbour primes are:
p q p*q+2
3 5 17
5 7 37
7 11 79
13 17 223
19 23 439
67 71 4759
149 151 22501
179 181 32401
229 233 53359
239 241 57601
241 251 60493
269 271 72901
277 281 77839
307 311 95479
313 317 99223
397 401 159199
401 409 164011
419 421 176401
439 443 194479
487 491 239119
Found 20 neighbour primes
done...

Wren[edit]

Library: Wren-math
Library: Wren-seq
Library: Wren-fmt
import "/math" for Int
import "/seq" for Lst
import "/fmt" for Fmt
 
var primes = Int.primeSieve(504)
var nprimes = []
System.print("Neighbour primes < 500:")
for (i in 0...primes.count-1) {
var p = primes[i] * primes[i+1] + 2
if (Int.isPrime(p)) nprimes.add(primes[i])
}
for (chunk in Lst.chunks(nprimes, 10)) Fmt.print("$3d", chunk)
System.print("\nFound %(nprimes.count) such primes.")
Output:
Neighbour primes < 500:
  3   5   7  13  19  67 149 179 229 239
241 269 277 307 313 397 401 419 439 487

Found 20 such primes.