Cuban primes: Difference between revisions
m
syntax highlighting fixup automation
SqrtNegInf (talk | contribs) m (→{{header|Raku}}: note use of 'ntheory' module) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 33:
=={{header|ALGOL 68}}==
<
# 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</
{{out}}
<pre>
Line 136:
=={{header|Bracmat}}==
{{trans|julia}}
<
=
. !arg:(?N.?bigN)
Line 208:
)
& cubanprimes$(200.100000)
)</
{{out}}
<pre>The first 200 cuban primes are:
Line 236:
=={{header|C}}==
{{trans|C++}}
<
#include <math.h>
#include <stdbool.h>
Line 347:
deallocate(&primes);
return 0;
}</
{{out}}
<pre>The first 200 cuban primes:
Line 376:
===using GMP===
So that we can go arbitrarily large, and it's faster to boot.
<
#include <stdio.h>
Line 411:
return 0;
}
</syntaxhighlight>
=={{header|C sharp|C#}}==
{{trans|Visual Basic .NET}}
(of the Snail Version)
<
using System.Collections.Generic;
using System.Linq;
Line 474:
if (System.Diagnostics.Debugger.IsAttached) Console.ReadKey();
}
}</
{{out}}
<pre>The first 200 cuban primes:
Line 504:
=={{header|C++}}==
{{trans|C#}}
<
#include <vector>
#include <chrono>
Line 564:
cout << "\nComputation time was " << elapsed_seconds.count() << " seconds" << endl;
return 0;
}</
{{out}}
<pre>The first 200 cuban primes:
Line 602:
with multiple columns, commas and all.
<
;;; Cuban primes are the difference of 2 consecutive cubes.
Line 638:
(car (last (cuban 100000))))
(princ #\newline)</
{{out}}
<pre>
Line 668:
=={{header|D}}==
{{trans|C#}}
<
import std.stdio;
Line 729:
}
writefln("\nThe %sth%s is %17s", c, tn, v);
}</
{{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#)]
<
// 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>
===The Task===
<
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>
{{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>
<
printfn "\n\n%s" (cL(Seq.item 99999 cubans))
</syntaxhighlight>
{{out}}
<pre>
Line 808:
=={{header|Factor}}==
{{trans|Sidef}}
<
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</
{{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">
include ./miller-rabin.fs
Line 893:
task2 cr
bye
</syntaxhighlight>
{{Out}}
<pre>
Line 920:
</pre>
=={{header|FreeBASIC}}==
<
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</
{{out}}
<pre>
Line 985:
=={{header|Go}}==
<
import (
Line 1,030:
}
fmt.Println("\nThe 100,000th cuban prime is", commatize(cube100k))
}</
{{out}}
Line 1,061:
=={{header|Groovy}}==
{{trans|Java}}
<
private static int MAX = 1_400_000
private static boolean[] primes = new boolean[MAX]
Line 1,116:
}
}
}</
{{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
<
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</
Where filter over map could also be expressed in terms of concatMap, or a list comprehension:
<
cubans =
[ x
| n <- [1 ..]
, let x = (succ n ^ 3) - (n ^ 3)
, isPrime x ]</
{{out}}
Line 1,200:
=={{header|J}}==
I've used assertions to demonstrate and to prove the defined verbs
<syntaxhighlight lang="j">
isPrime =: 1&p:
Line 1,263:
[: (#~ 1&p:) (-&(^&3)~ >:)
</syntaxhighlight>
=={{header|Java}}==
<syntaxhighlight lang="java">
public class CubanPrimes {
Line 1,324:
}
}
</syntaxhighlight>
{{out}}
<pre>
Line 1,365:
'''Preliminaries'''
<
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;</
'''The tasks'''
<syntaxhighlight 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)"</
{{out}}
<pre>
Line 1,426:
{{trans|Go}}
{{works with|Julia|1.2}}
<
function cubanprimes(N)
Line 1,451:
cubanprimes(200)
</
<pre>
The first 200 cuban primes are:
Line 1,485:
=={{header|Kotlin}}==
{{trans|D}}
<
import kotlin.math.sqrt
Line 1,547:
}
println("\nThe %dth cuban prime is %17d".format(c, v))
}</
{{out}}
<pre>The first 200 cuban primes:
Line 1,577:
===Original===
{{trans|D}}
<
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))</
{{out}}
<pre>The first 200 cuban primes
Line 1,674:
===Alternate===
Perhaps a more "readable" structure, and with specified formatting..
<
------------------
-- PRIME SUPPORT:
Line 1,716:
n = n + 1
end
</syntaxhighlight>
{{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: 7 19 37 ··· <br><br><br> It also appears that most of the program is missing. <br><br>}}
<
cp := Array([]);
for i by 2 while numelems(cp) < n do
Line 1,753:
end do;
return cp;
end proc;</
{{out}}
<pre> The first 200 cuban primes are
Line 1,761:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
While[Length[result] < m,
n++;
Line 1,768:
result]
cubans[200]
NumberForm[Last[cubans[100000]], NumberSeparator -> ",", DigitBlock -> 3]</
{{out}}
Line 1,800:
=={{header|Nim}}==
{{trans|C#}}
<
import strutils
import math
Line 1,852:
break
write(stdout, "\n")
echo fmt"The {c}th cuban prime is {insertSep($v, ',')}"</
{{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
<
{$IFDEF FPC}
{$MODE DELPHI}
Line 1,985:
OutFirstCntCubPrimes(200,10);
OutNthCubPrime(100000);
end.</
{{out}}
<pre> 7 19 37 61 127 271 331 397 547 631
Line 2,012:
=={{header|Perl}}==
{{libheader|ntheory}}
<
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]);
}</
{{out}}
<pre>
Line 2,077:
=={{header|Phix}}==
{{libheader|Phix/mpfr}}
<!--<
<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>
<!--</
{{out}}
<pre>
Line 2,142:
{{trans|C#}}
<syntaxhighlight 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>
{{out}}
Line 2,239:
=={{header|Racket}}==
<
(require math/number-theory
Line 2,276:
(progress-report x)
p)
(newline))</
{{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"
use ntheory:from<Perl5> <:all>;
Line 2,316:
put '';
put @cubans[99_999]., # zero indexed</
{{out}}
Line 2,348:
Here are the first 20 for each valid k up to 10:
<syntaxhighlight lang="raku"
for 2..10 -> \k {
Line 2,357:
put '';
}
</syntaxhighlight>
{{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"
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];</
<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 '''6*k + 1''', where '''k''' is any positive integer.
<
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 _</
This REXX program makes use of '''LINESIZE''' REXX program (or
BIF) which is used to determine the screen width
Line 2,472:
=={{header|Ring}}==
<
load "stdlib.ring"
Line 2,493:
see "done..." + nl
</syntaxhighlight>
Output:
<pre>
Line 2,501:
=={{header|Ruby}}==
<
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."</
{{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]
<
use separator::Separatable;
Line 2,592:
println!("The {}th cuban prime number is {}", LAST_CUBAN_PRIME, cuban.separated_string());
println!("Elapsed time: {:?}", elapsed);
}</
{{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.
<
import spire.implicits._
Line 2,664:
fHelper(Vector[String](), formatted)
}
}</
{{out}}
Line 2,690:
=={{header|Sidef}}==
<
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)</
{{out}}
<pre>
Line 2,728:
=={{header|Transd}}==
{{trans|Python}}
<
#lang transd
Line 2,776:
)
}
</
<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).
<
Dim primes As List(Of Long) = {3L, 5L}.ToList()
Line 2,841:
If System.Diagnostics.Debugger.IsAttached Then Console.ReadKey()
End Sub
End Module</
{{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.
<
Dim primes As List(Of Long) = {3L, 5L}.ToList()
Line 2,907:
If System.Diagnostics.Debugger.IsAttached Then Console.ReadKey()
End Sub
End Module</
{{out}}
<pre>The first 200 cuban primes:
Line 2,940:
{{trans|Python}}
{{libheader|Wren-fmt}}
<
var start = System.clock
Line 3,002:
System.print("\nThe 100,000th cuban prime is %(bigCuban)")
System.print("\nTook %(System.clock - start) secs")</
{{out}}
Line 3,038:
[[Extensible prime generator#zkl]] could be used instead.
<
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(_));</
{{out}}
<pre style="font-size:83%">
Line 3,075:
</pre>
Now lets get big.
<
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;
}</
{{out}}
<pre>
|