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)

Find prime numbers of the form n*n*n+2

From Rosetta Code
Find prime numbers of the form n*n*n+2 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 prime numbers of the form   n3+2,   where 0 < n < 200



AWK[edit]

 
# syntax: GAWK -f FIND_PRIME_NUMBERS_OF_THE_FORM_NNN2.AWK
BEGIN {
start = 1
stop = 200
for (n=start; n<=stop; n++) {
p = n*n*n + 2
if (is_prime(p)) {
printf("%3d %'10d\n",n,p)
count++
}
}
printf("Prime numbers %d-%d of the form n*n*n+2: %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:
  1          3
  3         29
  5        127
 29     24,391
 45     91,127
 63    250,049
 65    274,627
 69    328,511
 71    357,913
 83    571,789
105  1,157,627
113  1,442,899
123  1,860,869
129  2,146,691
143  2,924,209
153  3,581,579
171  5,000,213
173  5,177,719
189  6,751,271
Prime numbers 1-200 of the form n*n*n+2: 19

C[edit]

Translation of: Wren
#include <stdio.h>
#include <stdbool.h>
#include <locale.h>
 
bool isPrime(int n) {
int d;
if (n < 2) return false;
if (!(n%2)) return n == 2;
if (!(n%3)) return n == 3;
d = 5;
while (d*d <= n) {
if (!(n%d)) return false;
d += 2;
if (!(n%d)) return false;
d += 4;
}
return true;
}
 
int main() {
int n, p;
const int limit = 200;
setlocale(LC_ALL, "");
for (n = 1; n < limit; ++n) {
p = n*n*n + 2;
if (isPrime(p)) {
printf("n = %3d => n³ + 2 = %'9d\n", n, p);
}
}
return 0;
}
Output:
n =   1 => n³ + 2 =         3
n =   3 => n³ + 2 =        29
n =   5 => n³ + 2 =       127
n =  29 => n³ + 2 =    24,391
n =  45 => n³ + 2 =    91,127
n =  63 => n³ + 2 =   250,049
n =  65 => n³ + 2 =   274,627
n =  69 => n³ + 2 =   328,511
n =  71 => n³ + 2 =   357,913
n =  83 => n³ + 2 =   571,789
n = 105 => n³ + 2 = 1,157,627
n = 113 => n³ + 2 = 1,442,899
n = 123 => n³ + 2 = 1,860,869
n = 129 => n³ + 2 = 2,146,691
n = 143 => n³ + 2 = 2,924,209
n = 153 => n³ + 2 = 3,581,579
n = 171 => n³ + 2 = 5,000,213
n = 173 => n³ + 2 = 5,177,719
n = 189 => n³ + 2 = 6,751,271

Delphi[edit]

Library: PrimTrial
 
program Find_prime_numbers_of_the_form_n_n_n_plus_2;
 
{$APPTYPE CONSOLE}
 
uses
System.SysUtils,
PrimTrial;
 
function Commatize(n: NativeInt): string;
var
fmt: TFormatSettings;
begin
fmt := TFormatSettings.Create('en-Us');
Result := double(n).ToString(ffNumber, 64, 0, fmt);
end;
 
const
limit = 200;
 
begin
for var n := 1 to limit - 1 do
begin
var p := n * n * n + 2;
if isPrime(p) then
writeln('n = ', n: 3, ' => n^3 + 2 = ', Commatize(p): 9);
end;
readln;
end.
Output:
n =   1 => n^3 + 2 =         3
n =   3 => n^3 + 2 =        29
n =   5 => n^3 + 2 =       127
n =  29 => n^3 + 2 =    24,391
n =  45 => n^3 + 2 =    91,127
n =  63 => n^3 + 2 =   250,049
n =  65 => n^3 + 2 =   274,627
n =  69 => n^3 + 2 =   328,511
n =  71 => n^3 + 2 =   357,913
n =  83 => n^3 + 2 =   571,789
n = 105 => n^3 + 2 = 1,157,627
n = 113 => n^3 + 2 = 1,442,899
n = 123 => n^3 + 2 = 1,860,869
n = 129 => n^3 + 2 = 2,146,691
n = 143 => n^3 + 2 = 2,924,209
n = 153 => n^3 + 2 = 3,581,579
n = 171 => n^3 + 2 = 5,000,213
n = 173 => n^3 + 2 = 5,177,719
n = 189 => n^3 + 2 = 6,751,271

F#[edit]

This task uses Extensible Prime Generator (F#).

 
[1..2..200]|>Seq.filter(fun n->isPrime(2+pown n 3))|>Seq.iter(fun n->printfn "n=%3d -> %d" n (2+pown n 3))
 
Output:
n=  1 -> 3
n=  3 -> 29
n=  5 -> 127
n= 29 -> 24391
n= 45 -> 91127
n= 63 -> 250049
n= 65 -> 274627
n= 69 -> 328511
n= 71 -> 357913
n= 83 -> 571789
n=105 -> 1157627
n=113 -> 1442899
n=123 -> 1860869
n=129 -> 2146691
n=143 -> 2924209
n=153 -> 3581579
n=171 -> 5000213
n=173 -> 5177719
n=189 -> 6751271

Factor[edit]

Using the parity optimization from the Wren entry:

Works with: Factor version 0.99 2021-02-05
USING: formatting kernel math math.functions math.primes
math.ranges sequences tools.memory.private ;
 
1 199 2 <range> [
dup 3 ^ 2 + dup prime?
[ commas "n = %3d => n³ + 2 = %9s\n" printf ] [ 2drop ] if
] each

Or, using local variables:

Translation of: Wren
Works with: Factor version 0.99 2021-02-05
USING: formatting kernel math math.primes math.ranges sequences
tools.memory.private ;
 
[let
199 :> limit
1 limit 2 <range> [| n |
n n n * * 2 + :> p
p prime?
[ n p commas "n = %3d => n³ + 2 = %9s\n" printf ] when
] each
]
Output:
n =   1 => n³ + 2 =         3
n =   3 => n³ + 2 =        29
n =   5 => n³ + 2 =       127
n =  29 => n³ + 2 =    24,391
n =  45 => n³ + 2 =    91,127
n =  63 => n³ + 2 =   250,049
n =  65 => n³ + 2 =   274,627
n =  69 => n³ + 2 =   328,511
n =  71 => n³ + 2 =   357,913
n =  83 => n³ + 2 =   571,789
n = 105 => n³ + 2 = 1,157,627
n = 113 => n³ + 2 = 1,442,899
n = 123 => n³ + 2 = 1,860,869
n = 129 => n³ + 2 = 2,146,691
n = 143 => n³ + 2 = 2,924,209
n = 153 => n³ + 2 = 3,581,579
n = 171 => n³ + 2 = 5,000,213
n = 173 => n³ + 2 = 5,177,719
n = 189 => n³ + 2 = 6,751,271

Fermat[edit]

for n=1,199 do if Isprime(n^3+2)=1 then !!(n,n^3+2) fi od
Output:

1 3
3 29
5 127
29 24391
45 91127
63 250049
65 274627
69 328511
71 357913
83 571789
105 1157627
113 1442899
123 1860869
129 2146691
143 2924209
153 3581579
171 5000213
173 5177719
189 6751271

FreeBASIC[edit]

Use the code from Primality by trial division#FreeBASIC as an include.

#include"isprime.bas"
 
for n as uinteger = 1 to 200
if isprime(n^3+2) then
print n, n^3+2
end if
next n
Output:

1 3 3 29 5 127 29 24391 45 91127 63 250049 65 274627 69 328511 71 357913 83 571789 105 1157627 113 1442899 123 1860869 129 2146691 143 2924209 153 3581579 171 5000213 173 5177719 189 6751271

Go[edit]

package main
 
import "fmt"
 
func isPrime(n int) bool {
switch {
case n < 2:
return false
case n%2 == 0:
return n == 2
case n%3 == 0:
return n == 3
default:
d := 5
for d*d <= n {
if n%d == 0 {
return false
}
d += 2
if n%d == 0 {
return false
}
d += 4
}
return true
}
}
 
func commatize(n int) 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 main() {
const limit = 200
for n := 1; n < limit; n++ {
p := n*n*n + 2
if isPrime(p) {
fmt.Printf("n = %3d => n³ + 2 = %9s\n", n, commatize(p))
}
}
}
Output:
n =   1 => n³ + 2 =         3
n =   3 => n³ + 2 =        29
n =   5 => n³ + 2 =       127
n =  29 => n³ + 2 =    24,391
n =  45 => n³ + 2 =    91,127
n =  63 => n³ + 2 =   250,049
n =  65 => n³ + 2 =   274,627
n =  69 => n³ + 2 =   328,511
n =  71 => n³ + 2 =   357,913
n =  83 => n³ + 2 =   571,789
n = 105 => n³ + 2 = 1,157,627
n = 113 => n³ + 2 = 1,442,899
n = 123 => n³ + 2 = 1,860,869
n = 129 => n³ + 2 = 2,146,691
n = 143 => n³ + 2 = 2,924,209
n = 153 => n³ + 2 = 3,581,579
n = 171 => n³ + 2 = 5,000,213
n = 173 => n³ + 2 = 5,177,719
n = 189 => n³ + 2 = 6,751,271

Julia[edit]

# Formatting output as in Go example.
using Primes, Formatting
 
isncubedplus2prime(x) = begin fx = x * x * x + 2; (isprime(fx), fx) end
 
tostring(x, fx) = "n = " * lpad(x, 3) * " => n³ + 2 =" * lpad(format(fx, commas=true), 10)
 
function filterprintresults(x_to_bool_and_fx, start, stop, stringify=(x, fx)->"$x $fx", doprint=true)
ncount = 0
println("Filtering $x_to_bool_and_fx for integers between $start and $stop:\n")
for n in start+1:stop-1
isone, result = x_to_bool_and_fx(n)
if isone
doprint && println(stringify(n, result))
ncount += 1
end
end
println("\nThe total found was $ncount.")
end
 
filterprintresults(isncubedplus2prime, 0, 200, tostring)
 
Output:
n =   1 => n³ + 2 =         3
n =   3 => n³ + 2 =        29
n =   5 => n³ + 2 =       127
n =  29 => n³ + 2 =    24,391
n =  45 => n³ + 2 =    91,127
n =  63 => n³ + 2 =   250,049
n =  65 => n³ + 2 =   274,627
n =  69 => n³ + 2 =   328,511
n =  71 => n³ + 2 =   357,913
n =  83 => n³ + 2 =   571,789
n = 105 => n³ + 2 = 1,157,627
n = 113 => n³ + 2 = 1,442,899
n = 123 => n³ + 2 = 1,860,869
n = 129 => n³ + 2 = 2,146,691
n = 143 => n³ + 2 = 2,924,209
n = 153 => n³ + 2 = 3,581,579
n = 171 => n³ + 2 = 5,000,213
n = 173 => n³ + 2 = 5,177,719
n = 189 => n³ + 2 = 6,751,271

The total found was 19.

One-liner version[edit]

using Primes; println(filter(isprime, map(x -> x^3 + 2, 1:199)))
Output:

[3, 29, 127, 24391, 91127, 250049, 274627, 328511, 357913, 571789, 1157627, 1442899, 1860869, 2146691, 2924209, 3581579, 5000213, 5177719, 6751271]

PARI/GP[edit]

for(N=1,200,if(isprime(N^3+2),print(N," ",N^3+2)))
Output:

1 3 3 29 5 127 29 24391 45 91127 63 250049 65 274627 69 328511 71 357913 83 571789 105 1157627 113 1442899 123 1860869 129 2146691 143 2924209 153 3581579 171 5000213 173 5177719 189 6751271

Perl[edit]

use strict;
use warnings;
use feature 'say';
 
# basic task results
say join ' ', grep { is_prime $_ } map { $_**3 + 2 } grep { 0 != $_%2 } 1..199;
 
# generalize a bit, how many primes over a range of exponents and offsets?
use Math::AnyNum ':all'; # in order to handle large values
say ' ' . sprintf '%4d'x11 , 1..10;
for my $e (1..10) {
printf '%2d ', $e;
for my $o (1..10) {
printf '%4d', scalar grep { is_prime $_ } map { $_**$e + $o } 1..199;
}
print "\n";
}
Output:
3 29 127 24391 91127 250049 274627 328511 357913 571789 1157627 1442899 1860869 2146691 2924209 3581579 5000213 5177719 6751271

      1   2   3   4   5   6   7   8   9  10
 1   46  45  44  44  43  43  42  42  42  42
 2   34  17  29  34  12  19  49  19  24  32
 3    1  19  26  25  23  17  18   0  28  20
 4   30  13  20   1   7  12  28   7   6  11
 5    1  12  14  14  11   7  15  17  12   3
 6    1   5  19  11   3   2  24   0   7  11
 7    1  10   8   8   7   9   7   6   9   8
 8    7   7   7   1   2   5   9   5   1   8
 9    1   5   7   7   5   5   6   0   9   6
10    1   3   3   9   3   1   5   3   2   1

Phix[edit]

function pn3p2(integer n)
    integer n3p2 = power(n,3)+2
    return iff(is_prime(n3p2)?{n,n3p2}:0)
end function
sequence res = filter(apply(tagset(199,1,2),pn3p2),"!=",0)
printf(1,"Found %d primes of the form n^3+2:\n",length(res))
papply(true,printf,{1,{"n = %3d => n^3+2 = %,9d\n"},res})
Output:
Found 19 primes of the form n^3+2:
n =   1 => n^3+2 =         3
n =   3 => n^3+2 =        29
n =   5 => n^3+2 =       127
n =  29 => n^3+2 =    24,391
n =  45 => n^3+2 =    91,127
n =  63 => n^3+2 =   250,049
n =  65 => n^3+2 =   274,627
n =  69 => n^3+2 =   328,511
n =  71 => n^3+2 =   357,913
n =  83 => n^3+2 =   571,789
n = 105 => n^3+2 = 1,157,627
n = 113 => n^3+2 = 1,442,899
n = 123 => n^3+2 = 1,860,869
n = 129 => n^3+2 = 2,146,691
n = 143 => n^3+2 = 2,924,209
n = 153 => n^3+2 = 3,581,579
n = 171 => n^3+2 = 5,000,213
n = 173 => n^3+2 = 5,177,719
n = 189 => n^3+2 = 6,751,271

Raku[edit]

# 20210315 Raku programming solution
 
say ((1199)»³ »+»2).grep: *.is-prime
Output:
(3 29 127 24391 91127 250049 274627 328511 357913 571789 1157627 1442899 1860869 2146691 2924209 3581579 5000213 5177719 6751271)

REXX[edit]

Since REXX doesn't have a   isPrime   function,   this REXX program generates a number of primes such that some
numbers can be tested for primality directly,   other numbers have to be tested by trial division for primality.  

A suitable number was calculated to generate a number of primes such that about half of the computing time used to
test the numbers for primality could be directly determined their primality,   the other half of the computing time used
would use trial division.

Since the task's requirements are pretty straight-forward and easy,   a little extra code was added for presentation
(title and title separator line,   the count of primes found,   and commatization of the numbers).

/*REXX program  finds and displays      n       primes of the form:     n**3  +  2.     */
parse arg LO HI hp . /*obtain optional argument from the CL.*/
if LO=='' | LO=="," then LO= 0 /*Not specified? Then use the default.*/
if HI=='' | HI=="," then HI= 200 /* " " " " " " */
if hp=='' | hp=="," then hp= 19 /* " " " " " " */
h= max(iSqrt(HI**3), hp**3) /*a high prime to generate primes to. */
w= length( commas(HI**3) ) + 3
call genP /*build array of semaphores for primes.*/
say right('n', 20) ' (n**3 + 2)' /*display a title for the output list. */
say left('', 20 + w + 20, '─') /*display a sep for the output list. */
finds= 0 /*# of triplet strange primes (so far).*/
 
do j=LO+1 by 2 to HI-1 /*look for primes of form of: n**3 + 2 */
x= j**3 + 2
if x<[email protected].# then if \!.x then iterate /*Not a semaphore prime? Then skip it.*/
else nop /*the NOP matches up with the "THEN".*/
else do k=2 while @.k**2<=x /*perform a primality test by division.*/
if x//@.k==0 then iterate j
end /*k*/
finds= finds + 1 /*bump # primes found of form: n**3+2 */
say right(commas(j), 20) right( commas(x), w)
end /*j*/
 
say left('', 20 + w + 20, '─'); say /*display a sep for the output list. */
say 'Found ' commas(finds) ' primes in the form of: n**3 + 2'
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 ?
/*──────────────────────────────────────────────────────────────────────────────────────*/
iSqrt: procedure; parse arg x; r=0; q=1; do while q<=x; q=q*4; end
do while q>1; q=q%4; _=x-r-q; r=r%2; if _>=0 then do;x=_;r=r+q; end; end
return r
/*──────────────────────────────────────────────────────────────────────────────────────*/
genP: !.= 0; pad= left('', 9) /*placeholders for primes; width of #'s*/
@.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 ≤ h. */
do [email protected].#+2 by 2 to h /*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 five 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:
                   n   (n**3 + 2)
────────────────────────────────────────────────────
                   1            3
                   3           29
                   5          127
                  29       24,391
                  45       91,127
                  63      250,049
                  65      274,627
                  69      328,511
                  71      357,913
                  83      571,789
                 105    1,157,627
                 113    1,442,899
                 123    1,860,869
                 129    2,146,691
                 143    2,924,209
                 153    3,581,579
                 171    5,000,213
                 173    5,177,719
                 189    6,751,271
────────────────────────────────────────────────────

Found  19  primes in the form of:  n**3 + 2

Ring[edit]

 
load "stdlib.ring"
 
see "working..." + nl
 
for n = 1 to 200 step 2
pr = pow(n,3)+2
if isprime(pr)
see "n = " + n + " => n³+2 = " + pr + nl
ok
next
 
see "done..." + nl
 
Output:
working...
n = 1 => n³+2 = 3
n = 3 => n³+2 = 29
n = 5 => n³+2 = 127
n = 29 => n³+2 = 24391
n = 45 => n³+2 = 91127
n = 63 => n³+2 = 250049
n = 65 => n³+2 = 274627
n = 69 => n³+2 = 328511
n = 71 => n³+2 = 357913
n = 83 => n³+2 = 571789
n = 105 => n³+2 = 1157627
n = 113 => n³+2 = 1442899
n = 123 => n³+2 = 1860869
n = 129 => n³+2 = 2146691
n = 143 => n³+2 = 2924209
n = 153 => n³+2 = 3581579
n = 171 => n³+2 = 5000213
n = 173 => n³+2 = 5177719
n = 189 => n³+2 = 6751271
done...

Rust[edit]

// 202100327 Rust programming solution
 
use primes::is_prime;
 
fn main() {
 
let mut count = 0;
let begin = 0;
let end = 200;
 
println!("Find prime numbers of the form");
println!(" n => n³ + 2 ");
 
for n in begin+1..end-1 {
let m = n*n*n+2;
if is_prime(m) {
println!("{:4} => {}", n, m);
count += 1;
}
}
 
println!("Found {} such prime numbers where {} < n < {}.", count,begin,end);
}
Output:
Find prime numbers of the form
   n => n³ + 2
   1 => 3
   3 => 29
   5 => 127
  29 => 24391
  45 => 91127
  63 => 250049
  65 => 274627
  69 => 328511
  71 => 357913
  83 => 571789
 105 => 1157627
 113 => 1442899
 123 => 1860869
 129 => 2146691
 143 => 2924209
 153 => 3581579
 171 => 5000213
 173 => 5177719
 189 => 6751271
Found 19 such prime numbers where 0 < n < 200.

Wren[edit]

Library: Wren-math
Library: Wren-trait
Library: Wren-fmt

If n is even then n³ + 2 is also even, so we only need to examine odd values of n here.

import "/math" for Int
import "/trait" for Stepped
import "/fmt" for Fmt
 
var limit = 200
for (n in Stepped.new(1...limit, 2)) {
var p = n*n*n + 2
if (Int.isPrime(p)) Fmt.print("n = $3d => n³ + 2 = $,9d", n, p)
}
Output:
n =   1 => n³ + 2 =         3
n =   3 => n³ + 2 =        29
n =   5 => n³ + 2 =       127
n =  29 => n³ + 2 =    24,391
n =  45 => n³ + 2 =    91,127
n =  63 => n³ + 2 =   250,049
n =  65 => n³ + 2 =   274,627
n =  69 => n³ + 2 =   328,511
n =  71 => n³ + 2 =   357,913
n =  83 => n³ + 2 =   571,789
n = 105 => n³ + 2 = 1,157,627
n = 113 => n³ + 2 = 1,442,899
n = 123 => n³ + 2 = 1,860,869
n = 129 => n³ + 2 = 2,146,691
n = 143 => n³ + 2 = 2,924,209
n = 153 => n³ + 2 = 3,581,579
n = 171 => n³ + 2 = 5,000,213
n = 173 => n³ + 2 = 5,177,719
n = 189 => n³ + 2 = 6,751,271