Cuban primes: Difference between revisions

m
syntax highlighting fixup automation
m (→‎{{header|Raku}}: note use of 'ntheory' module)
m (syntax highlighting fixup automation)
Line 33:
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68">BEGIN
# find some cuban primes (using the definition: a prime p is a cuban prime if #
# p = n^3 - ( n - 1 )^3 #
Line 107:
IF cuban count MOD 10 /= 0 THEN print( ( newline ) ) FI;
print( ( "The ", commatise( max cuban ), " cuban prime is: ", commatise( final cuban ), newline ) )
END</langsyntaxhighlight>
{{out}}
<pre>
Line 136:
=={{header|Bracmat}}==
{{trans|julia}}
<langsyntaxhighlight Bracmatlang="bracmat">( ( cubanprimes
=
. !arg:(?N.?bigN)
Line 208:
)
& cubanprimes$(200.100000)
)</langsyntaxhighlight>
{{out}}
<pre>The first 200 cuban primes are:
Line 236:
=={{header|C}}==
{{trans|C++}}
<langsyntaxhighlight Clang="c">#include <limits.h>
#include <math.h>
#include <stdbool.h>
Line 347:
deallocate(&primes);
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>The first 200 cuban primes:
Line 376:
===using GMP===
So that we can go arbitrarily large, and it's faster to boot.
<langsyntaxhighlight Clang="c">#include <gmp.h>
#include <stdio.h>
 
Line 411:
return 0;
}
</syntaxhighlight>
</lang>
 
=={{header|C sharp|C#}}==
{{trans|Visual Basic .NET}}
(of the Snail Version)
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 474:
if (System.Diagnostics.Debugger.IsAttached) Console.ReadKey();
}
}</langsyntaxhighlight>
{{out}}
<pre>The first 200 cuban primes:
Line 504:
=={{header|C++}}==
{{trans|C#}}
<langsyntaxhighlight Cpplang="cpp">#include <iostream>
#include <vector>
#include <chrono>
Line 564:
cout << "\nComputation time was " << elapsed_seconds.count() << " seconds" << endl;
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>The first 200 cuban primes:
Line 602:
with multiple columns, commas and all.
 
<langsyntaxhighlight lang="lisp">;;; Show the first 200 and the 100,000th cuban prime.
;;; Cuban primes are the difference of 2 consecutive cubes.
 
Line 638:
(car (last (cuban 100000))))
 
(princ #\newline)</langsyntaxhighlight>
{{out}}
<pre>
Line 668:
=={{header|D}}==
{{trans|C#}}
<langsyntaxhighlight lang="d">import std.math;
import std.stdio;
 
Line 729:
}
writefln("\nThe %sth%s is %17s", c, tn, v);
}</langsyntaxhighlight>
{{out}}
<pre>The first 200 cuban primes:
Line 761:
===The functions===
This task uses [http://www.rosettacode.org/wiki/Extensible_prime_generator#The_function Extensible Prime Generator (F#)]
<langsyntaxhighlight lang="fsharp">
// Generate cuban primes. Nigel Galloway: June 9th., 2019
let cubans=Seq.unfold(fun n->Some(n*n*n,n+1L)) 1L|>Seq.pairwise|>Seq.map(fun(n,g)->g-n)|>Seq.filter(isPrime64)
let cL=let g=System.Globalization.CultureInfo("en-GB") in (fun (n:int64)->n.ToString("N0",g))
</syntaxhighlight>
</lang>
===The Task===
<langsyntaxhighlight lang="fsharp">
cubans|>Seq.take 200|>List.ofSeq|>List.iteri(fun n g->if n%8=7 then printfn "%12s" (cL(g)) else printf "%12s" (cL(g)))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 798:
1,422,097 1,426,231 1,442,827 1,451,161 1,480,519 1,484,737 1,527,247 1,570,357
</pre>
<langsyntaxhighlight lang="fsharp">
printfn "\n\n%s" (cL(Seq.item 99999 cubans))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 808:
=={{header|Factor}}==
{{trans|Sidef}}
<langsyntaxhighlight lang="factor">USING: formatting grouping io kernel lists lists.lazy math
math.primes sequences tools.memory.private ;
IN: rosetta-code.cuban-primes
Line 820:
 
1e5 cuban-primes last commas "100,000th cuban prime is: %s\n"
printf</langsyntaxhighlight>
{{out}}
<pre>
Line 849:
=={{header|Forth}}==
Uses [https://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test#Forth Miller Rabin Primality Test]
<syntaxhighlight lang="forth">
<lang Forth>
include ./miller-rabin.fs
 
Line 893:
task2 cr
bye
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 920:
</pre>
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">function isprime( n as ulongint ) as boolean
if n mod 2 = 0 then return false
for i as uinteger = 3 to int(sqr(n))+1 step 2
Line 956:
end if
i += 1
wend</langsyntaxhighlight>
{{out}}
<pre>
Line 985:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,030:
}
fmt.Println("\nThe 100,000th cuban prime is", commatize(cube100k))
}</langsyntaxhighlight>
 
{{out}}
Line 1,061:
=={{header|Groovy}}==
{{trans|Java}}
<langsyntaxhighlight lang="groovy">class CubanPrimes {
private static int MAX = 1_400_000
private static boolean[] primes = new boolean[MAX]
Line 1,116:
}
}
}</langsyntaxhighlight>
{{out}}
<pre> 7 19 37 61 127 271 331 397 547 631
Line 1,147:
Uses Data.Numbers.Primes library: http://hackage.haskell.org/package/primes-0.2.1.0/docs/Data-Numbers-Primes.html<br>
Uses Data.List.Split library: https://hackage.haskell.org/package/split-0.2.3.4/docs/Data-List-Split.html
<langsyntaxhighlight lang="haskell">import Data.Numbers.Primes (isPrime)
import Data.List (intercalate)
import Data.List.Split (chunksOf)
Line 1,161:
where
rows = chunksOf 10 . take 200
thousands = reverse . intercalate "," . chunksOf 3 . reverse . show</langsyntaxhighlight>
 
Where filter over map could also be expressed in terms of concatMap, or a list comprehension:
 
<langsyntaxhighlight lang="haskell">cubans :: [Int]
cubans =
[ x
| n <- [1 ..]
, let x = (succ n ^ 3) - (n ^ 3)
, isPrime x ]</langsyntaxhighlight>
 
{{out}}
Line 1,200:
=={{header|J}}==
I've used assertions to demonstrate and to prove the defined verbs
<syntaxhighlight lang="j">
<lang j>
 
isPrime =: 1&p:
Line 1,263:
[: (#~ 1&p:) (-&(^&3)~ >:)
</syntaxhighlight>
</lang>
 
=={{header|Java}}==
<syntaxhighlight lang="java">
<lang Java>
public class CubanPrimes {
 
Line 1,324:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,365:
 
'''Preliminaries'''
<langsyntaxhighlight lang="jq"># input should be a non-negative integer
def commatize:
def digits: tostring | explode | reverse;
Line 1,378:
def nwise($n):
def n: if length <= $n then . else .[0:$n] , (.[$n:] | n) end;
n;</langsyntaxhighlight>
'''The tasks'''
<syntaxhighlight lang="jq">
<lang jq>
# Emit an unbounded stream
# The differences between successive cubes: 3n(n+1)+1
Line 1,393:
([limit(.; cubanprimes) | commatize | lpad(10)] | nwise(10) | join(" "))),
 
"\nThe 100,000th cuban prime is \(nth(100000 - 1; cubanprimes) | commatize)"</langsyntaxhighlight>
{{out}}
<pre>
Line 1,426:
{{trans|Go}}
{{works with|Julia|1.2}}
<langsyntaxhighlight lang="julia">using Primes
 
function cubanprimes(N)
Line 1,451:
 
cubanprimes(200)
</langsyntaxhighlight>{{out}}
<pre>
The first 200 cuban primes are:
Line 1,485:
=={{header|Kotlin}}==
{{trans|D}}
<langsyntaxhighlight lang="scala">import kotlin.math.ceil
import kotlin.math.sqrt
 
Line 1,547:
}
println("\nThe %dth cuban prime is %17d".format(c, v))
}</langsyntaxhighlight>
{{out}}
<pre>The first 200 cuban primes:
Line 1,577:
===Original===
{{trans|D}}
<langsyntaxhighlight lang="lua">local primes = {3, 5}
local cutOff = 200
local bigUn = 100000
Line 1,646:
end
--print(string.format("\nThe %dth%s is %17d", c, tn, v)) -- why: correcting reported inaccuracy in output, 6/11/2020 db
print(string.format("\nThe %dth%s is %.0f", c, tn, v))</langsyntaxhighlight>
{{out}}
<pre>The first 200 cuban primes
Line 1,674:
===Alternate===
Perhaps a more "readable" structure, and with specified formatting..
<langsyntaxhighlight lang="lua">-- cuban primes in Lua (alternate version 6/12/2020 db)
------------------
-- PRIME SUPPORT:
Line 1,716:
n = n + 1
end
</syntaxhighlight>
</lang>
{{out}}
<pre> 7 19 37 61 127 271 331 397 547 631
Line 1,745:
{{incorrect|Maple|<br><br> The output is still incorrect. <br><br> It appears that the Maple solution isn't using a correct formula for computing cuban primes. <br><br> See output from other entries for the first 200 cuban primes. <br><br> The first three cuban primes are: &nbsp; &nbsp; &nbsp; 7 &nbsp; &nbsp; 19 &nbsp; &nbsp; 37 &nbsp; &nbsp; ··· <br><br><br> It also appears that most of the program is missing. <br><br>}}
 
<langsyntaxhighlight lang="maple">CubanPrimes := proc(n) local i, cp;
cp := Array([]);
for i by 2 while numelems(cp) < n do
Line 1,753:
end do;
return cp;
end proc;</langsyntaxhighlight>
{{out}}
<pre> The first 200 cuban primes are
Line 1,761:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">cubans[m_Integer] := Block[{n = 1, result = {}, candidate},
While[Length[result] < m,
n++;
Line 1,768:
result]
cubans[200]
NumberForm[Last[cubans[100000]], NumberSeparator -> ",", DigitBlock -> 3]</langsyntaxhighlight>
 
{{out}}
Line 1,800:
=={{header|Nim}}==
{{trans|C#}}
<langsyntaxhighlight lang="nim">import strformat
import strutils
import math
Line 1,852:
break
write(stdout, "\n")
echo fmt"The {c}th cuban prime is {insertSep($v, ',')}"</langsyntaxhighlight>
{{out}}
<pre>The first 200 cuban primes
Line 1,883:
100: 283,669; 1000: 65,524,807; 10000: 11,712,188,419; 100000: 1,792,617,147,127
 
<langsyntaxhighlight lang="pascal">program CubanPrimes;
{$IFDEF FPC}
{$MODE DELPHI}
Line 1,985:
OutFirstCntCubPrimes(200,10);
OutNthCubPrime(100000);
end.</langsyntaxhighlight>
{{out}}
<pre> 7 19 37 61 127 271 331 397 547 631
Line 2,012:
=={{header|Perl}}==
{{libheader|ntheory}}
<langsyntaxhighlight lang="perl">use feature 'say';
use ntheory 'is_prime';
 
Line 2,043:
for my $n (1 .. 6) {
say "10^$n-th cuban prime is: ", commify((cuban_primes(10**$n))[-1]);
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,077:
=={{header|Phix}}==
{{libheader|Phix/mpfr}}
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">include</span> <span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
Line 2,110:
<span style="color: #0000FF;">{</span><span style="color: #000000;">p3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">p</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_free</span><span style="color: #0000FF;">({</span><span style="color: #000000;">p3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">p</span><span style="color: #0000FF;">})</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">elapsed</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t0</span><span style="color: #0000FF;">)</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,142:
 
{{trans|C#}}
<syntaxhighlight lang="python">
<lang Python>
import datetime
import math
Line 2,210:
print ("The {:,}th{} is {:,}".format(c, tn, v))
print("Computation time was {} seconds".format((datetime.datetime.now() - st).seconds))
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,239:
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">#lang racket
 
(require math/number-theory
Line 2,276:
(progress-report x)
p)
(newline))</langsyntaxhighlight>
 
{{out}}
Line 2,307:
===The task (k == 1)===
Not the most efficient, but concise, and good enough for this task. Use the ntheory library for prime testing; gets it down to around 20 seconds.
<syntaxhighlight lang="raku" perl6line>use Lingua::EN::Numbers;
use ntheory:from<Perl5> <:all>;
 
Line 2,316:
put '';
 
put @cubans[99_999].&comma; # zero indexed</langsyntaxhighlight>
 
{{out}}
Line 2,348:
 
Here are the first 20 for each valid k up to 10:
<syntaxhighlight lang="raku" perl6line>sub comma { $^i.flip.comb(3).join(',').flip }
 
for 2..10 -> \k {
Line 2,357:
put '';
}
</syntaxhighlight>
</lang>
{{out}}
<pre>First 20 cuban primes where k = 2:
Line 2,385:
===k == 2^128===
Note that Raku has native support for arbitrarily large integers and does not need to generate primes to test for primality. Using k of 2^128; finishes in ''well'' under a second.
<syntaxhighlight lang="raku" perl6line>sub comma { $^i.flip.comb(3).join(',').flip }
 
my \k = 2**128;
put "First 10 cuban primes where k = {k}:";
.&comma.put for (lazy (0..Inf).map({ (($_+k)³ - .³)/k }).grep: *.is-prime)[^10];</langsyntaxhighlight>
<pre>First 10 cuban primes where k = 340282366920938463463374607431768211456:
115,792,089,237,316,195,423,570,985,008,687,908,160,544,961,995,247,996,546,884,854,518,799,824,856,507
Line 2,407:
Also, by their construction, cuban primes can't have a
factor of &nbsp; '''6*k + 1''', &nbsp; where &nbsp; '''k''' &nbsp; is any positive integer.
<langsyntaxhighlight lang="rexx">/*REXX program finds and displays a number of cuban primes or the Nth cuban prime. */
numeric digits 20 /*ensure enough decimal digits for #s. */
parse arg N . /*obtain optional argument from the CL.*/
Line 2,433:
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: parse arg _; do jc=length(_)-3 to 1 by -3; _=insert(',', _, jc); end; return _</langsyntaxhighlight>
This REXX program makes use of &nbsp; '''LINESIZE''' &nbsp; REXX program &nbsp; (or
BIF) &nbsp; which is used to determine the screen width &nbsp;
Line 2,472:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
load "stdlib.ring"
 
Line 2,493:
 
see "done..." + nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,501:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">require "openssl"
RE = /(\d)(?=(\d\d\d)+(?!\d))/ # Activesupport uses this for commatizing
Line 2,522:
puts "
100_000th cuban prime is #{commatize( cuban_primes.take(100_000).last)}
which took #{(Time.now-t0).round} seconds to calculate."</langsyntaxhighlight>
{{out}}
<pre> 7 19 37 61 127 271 331 397 547 631
Line 2,551:
=={{header|Rust}}==
Uses the libraries [https://crates.io/crates/primal primal] and [https://crates.io/crates/separator separator]
<langsyntaxhighlight lang="rust">use std::time::Instant;
use separator::Separatable;
 
Line 2,592:
println!("The {}th cuban prime number is {}", LAST_CUBAN_PRIME, cuban.separated_string());
println!("Elapsed time: {:?}", elapsed);
}</langsyntaxhighlight>
{{out}}
<pre>Calculating the first 200 cuban primes and the 100000th cuban prime...
Line 2,625:
 
Spire's SafeLong is used instead of Java's BigInt for performance.
<langsyntaxhighlight lang="scala">import spire.math.SafeLong
import spire.implicits._
 
Line 2,664:
fHelper(Vector[String](), formatted)
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,690:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func cuban_primes(n) {
1..Inf -> lazy.map {|k| 3*k*(k+1) + 1 }\
.grep{ .is_prime }\
Line 2,700:
}
 
say ("\n100,000th cuban prime is: ", cuban_primes(1e5).last.commify)</langsyntaxhighlight>
{{out}}
<pre>
Line 2,728:
=={{header|Transd}}==
{{trans|Python}}
<langsyntaxhighlight lang="scheme">
#lang transd
 
Line 2,776:
)
}
</langsyntaxhighlight>{{out}}
<pre>
7 19 37 61 127 271 331 397 547 631
Line 2,805:
===Corner Cutting Version===
This language doesn't have a built-in for a ''IsPrime()'' function, so I was surprised to find that this runs so quickly. It builds a list of primes while it is creating the output table. Since the last item on the table is larger than the square root of the 100,000<sup>th</sup> cuban prime, there is no need to continue adding to the prime list while checking up to the 100,000<sup>th</sup> cuban prime. I found a bit of a shortcut, if you skip the iterator by just the right amount, only one value is tested for the final result. It's hard-coded in the program, so if another final cuban prime were to be selected for output, the program would need a re-write. If not skipping ahead to the answer, it takes a few seconds over a minute to eventually get to it (see Snail Version below).
<langsyntaxhighlight lang="vbnet">Module Module1
Dim primes As List(Of Long) = {3L, 5L}.ToList()
 
Line 2,841:
If System.Diagnostics.Debugger.IsAttached Then Console.ReadKey()
End Sub
End Module</langsyntaxhighlight>
{{out}}
<pre>The first 200 cuban primes:
Line 2,869:
===Snail Version===
This one doesn't take any shortcuts. It could be sped up (Execution time about 15 seconds) by threading chunks of the search for the 100,000<sup>th</sup> cuban prime, but you would have to take a guess about how far to go, which would be hard-coded, so one might as well use the short-cut version if you are willing to overlook that difficulty.
<langsyntaxhighlight lang="vbnet">Module Program
Dim primes As List(Of Long) = {3L, 5L}.ToList()
 
Line 2,907:
If System.Diagnostics.Debugger.IsAttached Then Console.ReadKey()
End Sub
End Module</langsyntaxhighlight>
{{out}}
<pre>The first 200 cuban primes:
Line 2,940:
{{trans|Python}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight lang="ecmascript">import "/fmt" for Fmt
 
var start = System.clock
Line 3,002:
 
System.print("\nThe 100,000th cuban prime is %(bigCuban)")
System.print("\nTook %(System.clock - start) secs")</langsyntaxhighlight>
 
{{out}}
Line 3,038:
 
[[Extensible prime generator#zkl]] could be used instead.
<langsyntaxhighlight lang="zkl">var [const] BI=Import("zklBigNum"); // libGMP
cubans:=(1).walker(*).tweak('wrap(n){ // lazy iterator
p:=3*n*(n + 1) + 1;
Line 3,047:
 
cubans.drop(100_000 - cubans.n).value :
println("\nThe 100,000th cuban prime is: %,d".fmt(_));</langsyntaxhighlight>
{{out}}
<pre style="font-size:83%">
Line 3,075:
</pre>
Now lets get big.
<langsyntaxhighlight lang="zkl">k,z := BI(2).pow(128), 10;
println("First %d cuban primes where k = %,d:".fmt(z,k));
foreach n in ([BI(1)..]){
Line 3,081:
if(p.probablyPrime()){ println("%,d".fmt(p)); z-=1; }
if(z<=0) break;
}</langsyntaxhighlight>
{{out}}
<pre>
10,333

edits