Circular primes: Difference between revisions

m
→‎Embedded: Minor tidy
m (→‎Embedded: Commented-out example restored.)
m (→‎Embedded: Minor tidy)
 
(38 intermediate revisions by 19 users not shown)
Line 30:
* [[wp:Repunit|Wikipedia article - Repunit]].
* [[oeis:A016114|OEIS sequence A016114 - Circular primes]].
 
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68">BEGIN # find circular primes - primes where all cyclic permutations #
# of the digits are also prime #
# genertes a sieve of circular primes, only the first #
Line 98 ⟶ 96:
OD;
print( ( newline ) )
END</langsyntaxhighlight>
{{out}}
<pre>
First 19 circular primes: 2 3 5 7 11 13 17 37 79 113 197 199 337 1193 3779 11939 19937 193939 199933
</pre>
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw">begin % find circular primes - primes where all cyclic permutations %
% of the digits are also prime %
% sets p( 1 :: n ) to a sieve of primes up to n %
Line 174 ⟶ 171:
end for_i ;
end_circular:
end.</langsyntaxhighlight>
{{out}}
<pre>
First 19 circular primes: 2 3 5 7 11 13 17 37 79 113 197 199 337 1193 3779 11939 19937 193939 199933
</pre>
 
=={{header|AppleScript}}==
<syntaxhighlight lang="applescript">on isPrime(n)
if (n < 4) then return (n > 1)
if ((n mod 2 is 0) or (n mod 3 is 0)) then return false
repeat with i from 5 to (n ^ 0.5) div 1 by 6
if ((n mod i is 0) or (n mod (i + 2) is 0)) then return false
end repeat
return true
end isPrime
 
on isCircularPrime(n)
if (not isPrime(n)) then return false
set temp to n
set c to 0
repeat while (temp > 9)
set temp to temp div 10
set c to c + 1
end repeat
set p to (10 ^ c) as integer
set temp to n
repeat c times
set temp to temp mod p * 10 + temp div p
if ((temp < n) or (not isPrime(temp))) then return false
end repeat
return true
end isCircularPrime
 
-- Return the first c circular primes.
-- Takes 2 as read and checks only odd numbers thereafter.
on circularPrimes(c)
if (c < 1) then return {}
set output to {2}
set n to 3
set counter to 1
repeat until (counter = c)
if (isCircularPrime(n)) then
set end of output to n
set counter to counter + 1
end if
set n to n + 2
end repeat
return output
end circularPrimes
 
return circularPrimes(19)</syntaxhighlight>
 
{{output}}
<syntaxhighlight lang="applescript">{2, 3, 5, 7, 11, 13, 17, 37, 79, 113, 197, 199, 337, 1193, 3779, 11939, 19937, 193939, 199933}</syntaxhighlight>
 
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">perms: function [n][
str: repeat to :string n 2
result: new []
Line 215 ⟶ 262:
]
i: i + 1
]</langsyntaxhighlight>
 
{{out}}
Line 238 ⟶ 285:
193939
199933</pre>
 
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f CIRCULAR_PRIMES.AWK
BEGIN {
Line 288 ⟶ 333:
return(1)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
first 19 circular primes: 2 3 5 7 11 13 17 37 79 113 197 199 337 1193 3779 11939 19937 193939 199933
</pre>
 
 
=={{header|BASIC}}==
Rosetta Code problem: https://rosettacode.org/wiki/Circular_primes
by Jjuanhdez, 02/2023
 
==={{header|BASIC256}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="freebasic">p = 2
dp = 1
cont = 0
print("Primeros 19 primos circulares:")
while cont < 19
if isCircularPrime(p) then print p;" "; : cont += 1
p += dp
dp = 2
end while
end
 
function isPrime(v)
if v < 2 then return False
if v mod 2 = 0 then return v = 2
if v mod 3 = 0 then return v = 3
d = 5
while d * d <= v
if v mod d = 0 then return False else d += 2
end while
return True
end function
 
function isCircularPrime(p)
n = floor(log(p)/log(10))
m = 10^n
q = p
for i = 0 to n
if (q < p or not isPrime(q)) then return false
q = (q mod m) * 10 + floor(q / m)
next i
return true
end function</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
 
==={{header|FreeBASIC}}===
<syntaxhighlight lang="freebasic">#define floor(x) ((x*2.0-0.5) Shr 1)
 
Function isPrime(Byval p As Integer) As Boolean
If p < 2 Then Return False
If p Mod 2 = 0 Then Return p = 2
If p Mod 3 = 0 Then Return p = 3
Dim As Integer d = 5
While d * d <= p
If p Mod d = 0 Then Return False Else d += 2
If p Mod d = 0 Then Return False Else d += 4
Wend
Return True
End Function
 
Function isCircularPrime(Byval p As Integer) As Boolean
Dim As Integer n = floor(Log(p)/Log(10))
Dim As Integer m = 10^n, q = p
For i As Integer = 0 To n
If (q < p Or Not isPrime(q)) Then Return false
q = (q Mod m) * 10 + floor(q / m)
Next i
Return true
End Function
 
Dim As Integer p = 2, dp = 1, cont = 0
Print("Primeros 19 primos circulares:")
While cont < 19
If isCircularPrime(p) Then Print p;" "; : cont += 1
p += dp: dp = 2
Wend
Sleep</syntaxhighlight>
{{out}}
<pre>
Primeros 19 primos circulares:
2 3 5 7 11 13 17 37 79 113 197 199 337 1193 3779 11939 19937 193939 199933
</pre>
 
 
==={{header|PureBasic}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="PureBasic">Macro floor(x)
Round(x, #PB_Round_Down)
EndMacro
 
Procedure isPrime(v.i)
If v <= 1 : ProcedureReturn #False
ElseIf v < 4 : ProcedureReturn #True
ElseIf v % 2 = 0 : ProcedureReturn #False
ElseIf v < 9 : ProcedureReturn #True
ElseIf v % 3 = 0 : ProcedureReturn #False
Else
Protected r = Round(Sqr(v), #PB_Round_Down)
Protected f = 5
While f <= r
If v % f = 0 Or v % (f + 2) = 0
ProcedureReturn #False
EndIf
f + 6
Wend
EndIf
ProcedureReturn #True
EndProcedure
 
Procedure isCircularPrime(p.i)
n.i = floor(Log(p)/Log(10))
m.i = Pow(10, n)
q.i = p
For i.i = 0 To n
If q < p Or Not isPrime(q)
ProcedureReturn #False
EndIf
q = (q % m) * 10 + floor(q / m)
Next i
ProcedureReturn #True
EndProcedure
 
OpenConsole()
 
p.i = 2
dp.i = 1
cont.i = 0
PrintN("Primeros 19 primos circulares:")
While cont < 19
If isCircularPrime(p)
Print(Str(p) + " ")
cont + 1
EndIf
p + dp
dp = 2
Wend
 
PrintN(#CRLF$ + "--- terminado, pulsa RETURN---"): Input()
CloseConsole()</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
 
==={{header|Yabasic}}===
<syntaxhighlight lang="freebasic">p = 2
dp = 1
cont = 0
print("Primeros 19 primos circulares:")
while cont < 19
if isCircularPrime(p) then
print p," ";
cont = cont + 1
fi
p = p + dp
dp = 2
wend
end
 
sub isPrime(v)
if v < 2 return False
if mod(v, 2) = 0 return v = 2
if mod(v, 3) = 0 return v = 3
d = 5
while d * d <= v
if mod(v, d) = 0 then return False else d = d + 2 : fi
wend
return True
end sub
 
sub isCircularPrime(p)
n = floor(log(p)/log(10))
m = 10^n
q = p
for i = 0 to n
if (q < p or not isPrime(q)) return false
q = (mod(q, m)) * 10 + floor(q / m)
next i
return true
end sub</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
 
=={{header|C}}==
{{libheader|GMP}}
<langsyntaxhighlight lang="c">#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
Line 393 ⟶ 620:
test_repunit(49081);
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 409 ⟶ 636:
R(49081) is probably prime.
</pre>
 
=={{header|C++}}==
{{libheader|GMP}}
<langsyntaxhighlight lang="cpp">#include <cstdint>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <gmpxx.h>
 
Line 422 ⟶ 647:
bool is_prime(const integer& n, int reps = 50) {
return mpz_probab_prime_p(n.get_mpz_t(), reps);
}
 
std::string to_string(const integer& n) {
std::ostringstream out;
out << n;
return out.str();
}
 
Line 433 ⟶ 652:
if (!is_prime(p))
return false;
std::string str = p.get_str(to_string(p));
for (size_t i = 0, n = str.size(); i + 1 < n; ++i) {
std::rotate(str.begin(), str.begin() + 1, str.end());
Line 477 ⟶ 696:
std::cout << "Next 4 circular primes:\n";
p = next_repunit(p);
std::string str = p.get_str(to_string(p));
int digits = str.size();
for (int count = 0; count < 4; ) {
Line 496 ⟶ 715:
test_repunit(49081);
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 514 ⟶ 733:
=={{header|D}}==
{{trans|C}}
<langsyntaxhighlight Dlang="d">import std.bigint;
import std.stdio;
 
Line 610 ⟶ 829:
}
writeln;
}</langsyntaxhighlight>
{{out}}
<pre>First 19 circular primes:
2, 3, 5, 7, 11, 13, 17, 37, 79, 113, 197, 199, 337, 1193, 3779, 11939, 19937, 193939, 199933</pre>
 
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
Again note how the code is broken up into easy to distinguish subroutines that can be reused, as opposed to mashing everything together into a mass of code that is difficult to understand, debug or enhance.
 
<syntaxhighlight lang="Delphi">
procedure ShowCircularPrimes(Memo: TMemo);
{Show list of the first 19, cicular primes}
var I,Cnt: integer;
var S: string;
 
 
 
procedure RotateStr(var S: string);
{Rotate characters in string}
var I: integer;
var C: char;
begin
C:=S[Length(S)];
for I:=Length(S)-1 downto 1 do S[I+1]:=S[I];
S[1]:=C;
end;
 
 
function IsCircularPrime(N: integer): boolean;
{Test if all rotations of number are prime and}
{A rotation of the number hasn't been used before}
var I,P: integer;
var NS: string;
begin
Result:=False;
NS:=IntToStr(N);
for I:=1 to Length(NS)-1 do
begin
{Rotate string and convert to integer}
RotateStr(NS);
P:=StrToInt(NS);
{Exit if number is not prime or}
{Is prime, is less than N i.e. we've seen it before}
if not IsPrime(P) or (P<N) then exit;
end;
Result:=True;
end;
 
begin
S:='';
Cnt:=0;
{Look for circular primes and display 1st 19}
for I:=0 to High(I) do
if IsPrime(I) then
if IsCircularPrime(I) then
begin
Inc(Cnt);
S:=S+Format('%7D',[I]);
if Cnt>=19 then break;
If (Cnt mod 5)=0 then S:=S+CRLF;
end;
Memo.Lines.Add(S);
Memo.Lines.Add('Count = '+IntToStr(Cnt));
end;
 
 
</syntaxhighlight>
{{out}}
<pre>
2 3 5 7 11
13 17 37 79 113
197 199 337 1193 3779
11939 19937 193939 199933
Count = 19
Elapsed Time: 21.234 ms.
 
</pre>
 
 
=={{header|EasyLang}}==
{{trans|AWK}}
<syntaxhighlight lang="easylang">
fastfunc prime n .
if n mod 2 = 0 and n > 2
return 0
.
i = 3
sq = sqrt n
while i <= sq
if n mod i = 0
return 0
.
i += 2
.
return 1
.
func cycle n .
m = n
p = 1
while m >= 10
p *= 10
m = m div 10
.
return m + n mod p * 10
.
func circprime p .
if prime p = 0
return 0
.
p2 = cycle p
while p2 <> p
if p2 < p or prime p2 = 0
return 0
.
p2 = cycle p2
.
return 1
.
p = 2
while count < 19
if circprime p = 1
print p
count += 1
.
p += 1
.
</syntaxhighlight>
 
=={{header|F_Sharp|F#}}==
This task uses [http://www.rosettacode.org/wiki/Repunit_primes#F.23 rUnitP] and [http://www.rosettacode.org/wiki/Extensible_prime_generator#The_functions Extensible Prime Generator (F#)]
<lang fsharp>
<syntaxhighlight lang="fsharp">
// Circular primes - Nigel Galloway: September 13th., 2021
let fG n g=let rec fG y=if y=g then true else if y>g && isPrime y then fG(10*(y%n)+y/n) else false in fG(10*(g%n)+g/n)
Line 622 ⟶ 967:
let circP()=seq{yield! [2;3;5;7]; yield! fN [1;3;7;9] 10}
circP()|> Seq.take 19 |>Seq.iter(printf "%d "); printfn ""
printf "The first 5 repunit primes are "; rUnitP(10)|>Seq.take 5|>Seq.iter(fun n->printf $"R(%d{n}) "); printfn ""
let isPrimeI g=Open.Numeric.Primes.MillerRabin.IsProbablePrime(&g)
</syntaxhighlight>
printf "The first 5 repunit primes are "; Seq.initInfinite((+)1)|>Seq.filter(fun n->isPrimeI((10I**n-1I)/9I))|>Seq.take 5|>Seq.iter(fun n->printf $"R(%d{n}) "); printfn ""
</lang>
{{out}}
<pre>
Line 630 ⟶ 974:
The first 5 repunit primes are R(2) R(19) R(23) R(317) R(1031)
</pre>
 
=={{header|Factor}}==
Unfortunately Factor's miller-rabin test or bignums aren't quite up to the task of finding the next four circular prime repunits in a reasonable time. It takes ~90 seconds to check R(7)-R(1031).
{{works with|Factor|0.99 2020-03-02}}
<langsyntaxhighlight lang="factor">USING: combinators.short-circuit formatting io kernel lists
lists.lazy math math.combinatorics math.functions math.parser
math.primes sequences sequences.extras ;
Line 661 ⟶ 1,006:
 
"The next 4 circular primes, in repunit format, are:" print
4 prime-repunits ltake [ "R(%d) " printf ] leach nl</langsyntaxhighlight>
{{out}}
<pre>
Line 670 ⟶ 1,015:
R(19) R(23) R(317) R(1031)
</pre>
 
=={{header|Forth}}==
Forth only supports native sized integers, so we only implement the first part of the task.
<syntaxhighlight lang="forth">
<lang Forth>
create 235-wheel 6 c, 4 c, 2 c, 4 c, 2 c, 4 c, 6 c, 2 c,
does> swap 7 and + c@ ;
Line 730 ⟶ 1,074:
." The first 19 circular primes are:" cr .primes cr
bye
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 736 ⟶ 1,080:
2 3 5 7 11 13 17 37 79 113 197 199 337 1193 3779 11939 19937 193939 199933
</pre>
=={{header|FutureBasic}}==
<syntaxhighlight lang="future basic">
 
begin globals
=={{header|FreeBASIC}}==
_last1 = 7
<lang freebasic>#define floor(x) ((x*2.0-0.5)Shr 1)
CFTimeInterval t
byte n(_last1 +1) //array of digits
uint64 list(20), p10 = 1
short count, digits, first1 = _last1
n(_last1) = 2 //First number to check
end globals
 
local fn convertToNumber as uint64
Function isPrime(Byval p As Integer) As Boolean
short i = first1
If p < 2 Then Return False
uint64 nr = n(i)
If p Mod 2 = 0 Then Return p = 2
while i < _last1
If p Mod 3 = 0 Then Return p = 3
Dimi++ As: Integer dnr = 5nr * 10 + n(i)
wend
While d * d <= p
end fn = nr
If p Mod d = 0 Then Return False Else d += 2
If p Mod d = 0 Then Return False Else d += 4
Wend
Return True
End Function
 
void local fn increment( dgt as short )
Function isCircularPrime(Byval p As Integer) As Boolean
select n(dgt)
Dim As Integer n = floor(Log(p)/Log(10))
Dimcase As1, Integer7, m5 =: 10^n, q(dgt) += p2
Forcase i3 As Integer : if digits then n(dgt) = 07 Toelse n(dgt) = 5
case 9 If (q: < p Or Not isPrimen(qdgt)) Then Return= false1
if qdgt == (qfirst1 Modthen m)first1-- * 10: digits++ floor(q: /p10 m)*= 10
fn increment( dgt -1 )
Next i
case else : n(dgt)++
Return true
end select
End Function
end fn
 
local fn isPrime( v as uint64 ) as bool
Dim As Integer p = 2, dp = 1, cont = 0
if v < 4 then exit fn = yes
Print("Primeros 19 primos circulares:")
if v mod 3 == 0 then exit fn = no
While cont < 19
uint64 f = 5
If isCircularPrime(p) Then Print p;" "; : cont += 1
while f*f p += dp: dp <= 2v
if v mod f == 0 then exit fn = no
Wend
f += 2
Sleep</lang>
if v mod f == 0 then exit fn = no
f += 4
wend
end fn = yes
 
void local fn circularPrimes
uint64 num, nr
short r
while ( count < 19 )
num = fn convertToNumber
if fn isPrime( num )
nr = num
for r = 1 to digits
nr = 10 * ( nr mod p10 ) + ( nr / p10 ) //Rotate
if nr < num then break //Rotation of lower number
if fn isPrime( nr ) == no then break //Not prime
next
if r > digits then list( count ) = num : count++
end if
fn increment( _last1 )
wend
end fn
 
window 1, @"Circular Primes in FutureBasic", (0, 0, 280, 320)
t = fn CACurrentMediaTime
fn circularPrimes
t = fn CACurrentMediaTime - t
for count = 0 to 18
printf @"%22u",list(count)
next
printf @"\n Compute time: %.3f ms", t * 1000
handleevents
 
</syntaxhighlight>
{{out}}
[[File:Screenshot of Circular Primes in FutureBasic.png]]
<pre>
Primeros 19 primos circulares:
2 3 5 7 11 13 17 37 79 113 197 199 337 1193 3779 11939 19937 193939 199933
</pre>
 
=={{header|Go}}==
{{libheader|GMP(Go wrapper)}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 900 ⟶ 1,280:
fmt.Printf("R(%-5d) : %t\n", i, repunit(i).ProbablyPrime(10))
}
}</langsyntaxhighlight>
 
{{out}}
Line 918 ⟶ 1,298:
R(49081) : true
</pre>
 
=={{header|Haskell}}==
Uses arithmoi Library: http://hackage.haskell.org/package/arithmoi-0.10.0.0
<langsyntaxhighlight lang="haskell">import Math.NumberTheory.Primes (Prime, unPrime, nextPrime)
import Math.NumberTheory.Primes.Testing (isPrime, millerRabinV)
import Text.Printf (printf)
Line 972 ⟶ 1,353:
circular = show . take 19 . filter (isCircular False)
reps = map (sum . digits). tail . take 5 . filter (isCircular True)
checkReps = (,) <$> id <*> show . isCircular True . asRepunit</langsyntaxhighlight>
{{out}}
<pre>
Line 991 ⟶ 1,372:
</pre>
=={{header|J}}==
<syntaxhighlight lang="j">
<lang J>
 
R=: [:10x "#. 'x' ,~ #&'1'
assert 11111111111111111111111111111111x -: R 32
 
Line 1,027 ⟶ 1,408:
group </. P
)
</syntaxhighlight>
</lang>
J lends itself to investigation. Demonstrate and play with the definitions.
<pre>
Line 1,064 ⟶ 1,445:
<pre>
Note 'The current Miller-Rabin test implemented in c is insufficient for this task'
R=: ([:10x "#. 'x' ,~ #&'1')&>
(;q:@R)&> 500
|limit error
Line 1,073 ⟶ 1,454:
Filter=: (#~`)(`:6)
 
R=: ([:10x "#. 'x' ,~ #&'1')&>
(; q:@R)&> (0 ~: 3&|)Filter >: i. 26 NB. factor some repunits
┌──┬─────────────────────────────────┐
Line 1,117 ⟶ 1,498:
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">import java.math.BigInteger;
import java.util.Arrays;
 
Line 1,207 ⟶ 1,588:
return new BigInteger(new String(ch));
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,220 ⟶ 1,601:
R(25031) is not prime.
</pre>
 
=={{header|jq}}==
{{works with|jq}}
Line 1,230 ⟶ 1,610:
 
For an implementation of `is_prime` suitable for the first task, see for example [[Erd%C5%91s-primes#jq]].
<syntaxhighlight lang="jq">
<lang jq>
def is_circular_prime:
def circle: range(0;length) as $i | .[$i:] + .[:$i];
Line 1,243 ⟶ 1,623:
def repunits:
1 | recurse(10*. + 1);
</syntaxhighlight>
</lang>
'''The first task'''
<syntaxhighlight lang ="jq">limit(19; circular_primes)</langsyntaxhighlight>
'''The second task''' (viewed independently):
<syntaxhighlight lang="jq">
<lang jq>
last(limit(19; circular_primes)) as $max
| limit(4; repunits | select(. > $max and is_prime))
| "R(\(tostring|length))"</langsyntaxhighlight>
{{out}}
For the first task:
Line 1,274 ⟶ 1,654:
199933
</pre>
 
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">using Lazy, Primes
Note that the evalpoly function used in this program was added in Julia 1.4
<lang julia>using Lazy, Primes
 
function iscircularprime(n)
Line 1,298 ⟶ 1,675:
println("R($i) is ", isprimerepunit(i) ? "prime." : "not prime.")
end
</langsyntaxhighlight>{{out}}
<pre>
The first 19 circular primes are:
Line 1,316 ⟶ 1,693:
=={{header|Kotlin}}==
{{trans|C}}
<langsyntaxhighlight lang="scala">import java.math.BigInteger
 
val SMALL_PRIMES = listOf(
Line 1,433 ⟶ 1,810:
testRepUnit(35317)
testRepUnit(49081)
}</langsyntaxhighlight>
{{out}}
<pre>First 19 circular primes:
Line 1,444 ⟶ 1,821:
R(25031) is not prime.
R(35317) is not prime.</pre>
 
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">-- Circular primes, in Lua, 6/22/2020 db
local function isprime(n)
if n < 2 then return false end
Line 1,473 ⟶ 1,848:
p, dp = p + dp, 2
end
print(table.concat(list, ", "))</langsyntaxhighlight>
{{out}}
<pre>2, 3, 5, 7, 11, 13, 17, 37, 79, 113, 197, 199, 337, 1193, 3779, 11939, 19937, 193939, 199933</pre>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">ClearAll[RepUnit, CircularPrimeQ]
RepUnit[n_] := (10^n - 1)/9
CircularPrimeQ[n_Integer] := Module[{id = IntegerDigits[n], nums, t},
Line 1,504 ⟶ 1,878:
]
 
Scan[Print@*PrimeQ@*RepUnit, {5003, 9887, 15073, 25031, 35317, 49081}]</langsyntaxhighlight>
{{out}}
<pre>{2, 3, 5, 7, 11, 13, 17, 37, 79, 113, 197, 199, 337, 1193, 3779, 11939, 19937, 193939, 199933}
Line 1,514 ⟶ 1,888:
False
True</pre>
 
=={{header|Nim}}==
{{trans|Kotlin}}
{{libheader|bignum}}
<langsyntaxhighlight Nimlang="nim">import bignum
import strformat
 
Line 1,628 ⟶ 2,001:
testRepUnit(25031)
testRepUnit(35317)
testRepUnit(49081)</langsyntaxhighlight>
 
{{out}}
Line 1,643 ⟶ 2,016:
R(35317) is not prime.
R(49081) is probably prime.</pre>
=={{header|Pascal}}==
==={{header|Free Pascal}}===
Only test up to 14 digit numbers.RepUnit test with gmp is to boring.<BR>
Using a base 4 downcounter to create the numbers with more than one digit.<br>
Changed the manner of the counter, so that it counts that there is no digit smaller than the first.
199-> 333 and not 311 so a base4 counter 1_(1,3,7,9) changed to base3 3_( 3,7,9 )->base2 7_(7,9) -> base 1 = 99....99.
The main speed up is reached by testing with small primes within CycleNum.
<syntaxhighlight lang="pascal">
program CircularPrimes;
//nearly the way it is done:
//http://www.worldofnumbers.com/circular.htm
//base 4 counter to create numbers with first digit is the samallest used.
//check if numbers are tested before and reduce gmp-calls by checking with prime 3,7
 
{$IFDEF FPC}
{$MODE DELPHI}{$OPTIMIZATION ON,ALL}
uses
Sysutils,gmp;
{$ENDIF}
{$IFDEF Delphi}
uses
System.Sysutils,?gmp?;
{$ENDIF}
 
{$IFDEF WINDOWS}
{$APPTYPE CONSOLE}
{$ENDIF}
const
MAXCNTOFDIGITS = 14;
MAXDGTVAL = 3;
conv : array[0..MAXDGTVAL+1] of byte = (9,7,3,1,0);
type
tDigits = array[0..23] of byte;
tUint64 = NativeUint;
var
mpz : mpz_t;
digits,
revDigits : tDigits;
CheckNum : array[0..19] of tUint64;
Found : array[0..23] of tUint64;
Pot_ten,Count,CountNumCyc,CountNumPrmTst : tUint64;
 
procedure CheckOne(MaxIdx:integer);
var
Num : Uint64;
i : integer;
begin
i:= MaxIdx;
repeat
inc(CountNumPrmTst);
num := CheckNum[i];
mpz_set_ui(mpz,Num);
If mpz_probab_prime_p(mpz,3)=0then
EXIT;
dec(i);
until i < 0;
Found[Count] := CheckNum[0];
inc(count);
end;
 
function CycleNum(MaxIdx:integer):Boolean;
//first create circular numbers to minimize prime checks
var
cycNum,First,P10 : tUint64;
i,j,cv : integer;
Begin
i:= MaxIdx;
j := 0;
First := 0;
repeat
cv := conv[digits[i]];
dec(i);
First := First*10+cv;
revDigits[j]:= cv;
inc(j);
until i < 0;
// if num is divisible by 3 then cycle numbers also divisible by 3 same sum of digits
IF First MOD 3 = 0 then
EXIT(false);
If First mod 7 = 0 then
EXIT(false);
 
//if one of the cycled number must have been tested before break
P10 := Pot_ten;
i := 0;
j := 0;
CheckNum[j] := First;
cycNum := First;
repeat
inc(CountNumCyc);
cv := revDigits[i];
inc(j);
cycNum := (cycNum - cv*P10)*10+cv;
//num was checked before
if cycNum < First then
EXIT(false);
if cycNum mod 7 = 0 then
EXIT(false);
CheckNum[j] := cycNum;
inc(i);
until i >= MaxIdx;
EXIT(true);
end;
 
var
T0: Int64;
 
idx,MaxIDx,dgt,MinDgt : NativeInt;
begin
T0 := GetTickCount64;
mpz_init(mpz);
 
fillchar(digits,Sizeof(digits),chr(MAXDGTVAL));
Count :=0;
For maxIdx := 2 to 10 do
if maxidx in[2,3,5,7] then
begin
Found[Count]:= maxIdx;
inc(count);
end;
 
Pot_ten := 10;
maxIdx := 1;
idx := 0;
MinDgt := MAXDGTVAL;
repeat
if CycleNum(MaxIdx) then
CheckOne(MaxIdx);
idx := 0;
repeat
dgt := digits[idx]-1;
if dgt >=0 then
break;
digits[idx] := MinDgt;
inc(idx);
until idx >MAXCNTOFDIGITS-1;
 
if idx > MAXCNTOFDIGITS-1 then
BREAK;
 
if idx<=MaxIDX then
begin
digits[idx] := dgt;
//change all to leading digit
if idx=MaxIDX then
Begin
For MinDgt := 0 to idx do
digits[MinDgt]:= dgt;
minDgt := dgt;
end;
end
else
begin
minDgt := MAXDGTVAL;
For maxidx := 0 to idx do
digits[MaxIdx] := MAXDGTVAL;
Maxidx := idx;
Pot_ten := Pot_ten*10;
writeln(idx:7,count:7,CountNumCyc:16,CountNumPrmTst:12,GetTickCount64-T0:8);
end;
until false;
writeln(idx:7,count:7,CountNumCyc:16,CountNumPrmTst:12,GetTickCount64-T0:8);
T0 := GetTickCount64-T0;
 
For idx := 0 to count-2 do
write(Found[idx],',');
writeln(Found[count-1]);
 
writeln('It took ',T0,' ms ','to check ',MAXCNTOFDIGITS,' decimals');
mpz_clear(mpz);
{$IFDEF WINDOWS}
readln;
{$ENDIF}
end.
</syntaxhighlight>
{{Out|@ Tio.Run}}
<pre>
Digits found cycles created primetests time in ms
2 9 7 10 0
3 13 43 38 0
4 15 203 89 0
5 17 879 213 0
6 19 4209 816 1
7 19 16595 1794 2
8 19 67082 4666 6
9 19 270760 13108 19
10 19 1094177 39059 63
11 19 4421415 118787 220
12 19 23728859 1078484 1505
13 19 77952009 1869814 3562
14 19 296360934 4405393 11320
#### 14 19 754020918 28736408 26129 ##### before
2,3,5,7,11,13,17,37,79,113,197,199,337,1193,3779,11939,19937,193939,199933
It took 11320 ms to check 14 decimals
 
only creating numbers
14 4 0 0 184
creating and cycling numbers testing not ( MOD 3=0 OR MoD 7 = 0)
14 4 247209700 0 8842
that reduces the count of gmp-prime tests to 1/6 </pre>
=={{header|Perl}}==
{{trans|Raku}}
{{libheader|ntheory}}
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use feature 'say';
Line 1,681 ⟶ 2,253:
for (5003, 9887, 15073, 25031, 35317, 49081) {
say "R($_): Prime? " . (is_prime 1 x $_ ? 'True' : 'False');
}</langsyntaxhighlight>
{{out}}
<pre>The first 19 circular primes are:
Line 1,699 ⟶ 2,271:
R(35317): Prime? False
R(49081): Prime? True</pre>
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">circular</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">p</span><span style="color: #0000FF;">)</span>
Line 1,721 ⟶ 2,292:
<span style="color: #000000;">n</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"The first 19 circular primes are:\n%Vv\n\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">c</span><span style="color: #0000FF;">})</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 1,739 ⟶ 2,310:
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"The next 4 circular primes, in repunit format, are:\n%s\n\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">)})</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 1,751 ⟶ 2,322:
===stretch===
<small>(It is probably quite unwise to throw this in the direction of pwa/p2js, I am not even going to bother trying.)</small>
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #008080;">constant</span> <span style="color: #000000;">t</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">5003</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">9887</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">15073</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">25031</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">35317</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">49081</span><span style="color: #0000FF;">}</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"The following repunits are probably circular primes:\n"</span><span style="color: #0000FF;">)</span>
Line 1,761 ⟶ 2,332:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"R(%d) : %t (%s)\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">ti</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">bPrime</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>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
{{out}}
64-bit can only cope with the first five (it terminates abruptly on the sixth)<br>
Line 1,783 ⟶ 2,354:
diag looping, error code is 1, era is #00644651
</pre>
=={{header|PicoLisp}}==
For small primes, I only check numbers that are made up of the digits 1, 3, 7, and 9, and I also use a small prime checker to avoid the overhead of the Miller-Rabin Primality Test. For the large repunits, one can use the code from the Miller Rabin task.
<syntaxhighlight lang="picolisp">
(load "plcommon/primality.l") # see task: "Miller-Rabin Primality Test"
 
(de candidates (Limit)
(let Q (0)
(nth
(sort
(make
(while Q
(let A (pop 'Q)
(when (< A Limit)
(link A)
(setq Q
(cons
(+ (* 10 A) 1)
(cons
(+ (* 10 A) 3)
(cons
(+ (* 10 A) 7)
(cons (+ (* 10 A) 9) Q))))))))))
6)))
 
(de circular? (P0)
(and
(small-prime? P0)
(fully '((P) (and (>= P P0) (small-prime? P))) (rotations P0))))
 
(de rotate (L)
(let ((X . Xs) L)
(append Xs (list X))))
 
(de rotations (N)
(let L (chop N)
(mapcar
format
(make
(do (dec (length L))
(link (setq L (rotate L))))))))
 
(de small-prime? (N) # For small prime candidates only
(if (< N 2)
NIL
(let W (1 2 2 . (4 2 4 2 4 6 2 6 .))
(for (D 2 T (+ D (pop 'W)))
(T (> (* D D) N) T)
(T (=0 (% N D)) NIL)))))
 
(de repunit-primes (N)
(let (Test 111111 Remaining N K 6)
(make
(until (=0 Remaining)
(setq Test (inc (* 10 Test)))
(inc 'K)
(when (prime? Test)
(link K)
(dec 'Remaining))))))
 
(setq Circular
(conc
(2 3 5 7)
(filter circular? (candidates 1000000))
(mapcar '((X) (list 'R X)) (repunit-primes 4))))
 
(prinl "The first few circular primes:")
(println Circular)
(bye)
</syntaxhighlight>
{{Out}}
<pre>
The first few circular primes:
(2 3 5 7 11 13 17 37 79 113 197 199 337 1193 3779 11939 19937 193939 199933 (R 19) (R 23) (R 317) (R 1031))
</pre>
=={{header|Prolog}}==
Uses a miller-rabin primality tester that I wrote which includes a trial division pass for small prime factors. One could substitute with e.g. the Miller Rabin Primaliy Test task.
Line 1,790 ⟶ 2,434:
 
Also the code is smart in that it only checks primes > 9 that are composed of the digits 1, 3, 7, and 9.
<syntaxhighlight lang="prolog">
<lang Prolog>
?- use_module(library(primality)).
 
Line 1,831 ⟶ 2,475:
 
?- main.
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,837 ⟶ 2,481:
[2,3,5,7,11,13,17,37,79,113,197,199,337,1193,3779,11939,19937,193939,199933,r(19),r(23),r(317),r(1031)]
</pre>
 
=={{header|Python}}==
<syntaxhighlight lang="python">
<lang Python>
import random
 
Line 1,952 ⟶ 2,595:
 
# because this Miller-Rabin test is already on rosettacode there's no good reason to test the longer repunits.
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Most of the repunit testing is relatively speedy using the ntheory library. The really slow ones are R(25031), at ~42 seconds and R(49081) at 922(!!) seconds.
{{libheader|ntheory}}
 
<syntaxhighlight lang="raku" line>sub isCircular(\n) {
<lang perl6>#!/usr/bin/env raku
 
# 20200406 Raku programming solution
 
sub isCircular(\n) {
return False unless n.is-prime;
my @circular = n.comb;
Line 1,986 ⟶ 2,624:
my $now = now;
say "R($_): Prime? ", ?is_prime("{1 x $_}"), " {(now - $now).fmt: '%.2f'}"
}</langsyntaxhighlight>
{{out}}
<pre>The first 19 circular primes are:
Line 2,004 ⟶ 2,642:
R(35317): Prime? False 0.32
R(49081): Prime? True 921.73</pre>
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX program finds & displays circular primes (with a title & in a horizontal format).*/
parse arg N hp . /*obtain optional arguments from the CL*/
if N=='' | N=="," then N= 19 /* " " " " " " */
Line 2,042 ⟶ 2,679:
end /*k*/ /* [↓] a prime (J) has been found. */
#= #+1; !.j= 1; sq.#= j*j; @.#= j /*bump P cnt; assign P to @. and !. */
end /*j*/; return</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 2,049 ⟶ 2,686:
2 3 5 7 11 13 17 37 79 113 197 199 337 1193 3779 11939 19937 193939 199933
</pre>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
see "working..." + nl
see "First 19 circular numbers are:" + nl
Line 2,095 ⟶ 2,731:
next
return 1
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,105 ⟶ 2,741:
11939 19937 193939 199933
done...
</pre>
=={{header|RPL}}==
To speed up execution, we use a generator of candidate numbers made only of 1, 3, 7 and 9.
{{works with|HP|49}}
≪ 1 SF DUP
'''DO'''
→STR TAIL LASTARG HEAD + STR→
'''CASE'''
DUP2 > OVER 3 MOD NOT OR '''THEN''' 1 CF '''END'''
DUP ISPRIME? NOT '''THEN''' 1 CF '''END'''
'''END'''
'''UNTIL''' DUP2 == 1 FC? OR '''END'''
DROP2 1 FS?
≫ '<span style="color:blue">CIRC?</span>' STO
≪ →STR "9731" → prev digits
≪ 1 SF "" <span style="color:grey">@ flag 1 set = carry</span>
prev SIZE 1 '''FOR''' j
digits DUP
prev j DUP SUB POS 1 FS? -
'''IF''' DUP NOT '''THEN''' DROP digits SIZE '''ELSE''' 1 CF '''END'''
DUP SUB SWAP +
-1 '''STEP'''
'''IF''' 1 FS? '''THEN''' digits DUP SIZE DUP SUB SWAP + '''END'''
STR→
≫ ≫ '<span style="color:blue">NEXT1379</span>' STO
≪ 2 CF { 2 3 5 7 } 7
DO
<span style="color:blue">NEXT1379</span>
'''IF''' DUP <span style="color:blue">CIRC?</span> '''THEN'''
SWAP OVER + SWAP
'''IF''' OVER SIZE 19 ≥ '''THEN''' 2 SF '''END'''
'''END'''
'''UNTIL''' 2 FS? '''END''' DROP
≫ '<span style="color:blue">TASK</span>' STO
{{out}}
<pre>
1: { 2 3 5 7 11 13 17 37 79 113 197 199 337 1193 3779 11939 19937 193939 199933 }
</pre>
Runs in 13 minutes 10 seconds on a HP-50g.
 
=={{header|Ruby}}==
It takes more then 25 minutes to verify that R49081 is probably prime - omitted here.
<syntaxhighlight lang="ruby">require 'gmp'
require 'prime'
candidate_primes = Enumerator.new do |y|
DIGS = [1,3,7,9]
[2,3,5,7].each{|n| y << n.to_s}
(2..).each do |size|
DIGS.repeated_permutation(size) do |perm|
y << perm.join if (perm == min_rotation(perm)) && GMP::Z(perm.join).probab_prime? > 0
end
end
end
 
def min_rotation(ar) = Array.new(ar.size){|n| ar.rotate(n)}.min
 
def circular?(num_str)
chars = num_str.chars
return GMP::Z(num_str).probab_prime? > 0 if chars.all?("1")
chars.size.times.all? do
GMP::Z(chars.rotate!.join).probab_prime? > 0
# chars.rotate!.join.to_i.prime?
end
end
 
puts "First 19 circular primes:"
puts candidate_primes.lazy.select{|cand| circular?(cand)}.take(19).to_a.join(", "),""
puts "First 5 prime repunits:"
reps = Prime.each.lazy.select{|pr| circular?("1"*pr)}.take(5).to_a
puts reps.map{|r| "R" + r.to_s}.join(", "), ""
[5003, 9887, 15073, 25031].each {|rep| puts "R#{rep} circular_prime ? #{circular?("1"*rep)}" }
</syntaxhighlight>
{{out}}
<pre>First 19 circular primes:
2, 3, 5, 7, 11, 13, 17, 37, 79, 113, 197, 199, 337, 1193, 3779, 11939, 19937, 193939, 199933
 
First 5 prime repunits:
R2, R19, R23, R317, R1031
 
R5003 circular_prime ? false
R9887 circular_prime ? false
R15073 circular_prime ? false
R25031 circular_prime ? false
</pre>
 
=={{header|Rust}}==
{{trans|C}}
<langsyntaxhighlight lang="rust">// [dependencies]
// rug = "1.8"
 
Line 2,214 ⟶ 2,935:
test_repunit(35317);
test_repunit(49081);
}</langsyntaxhighlight>
 
{{out}}
Line 2,230 ⟶ 2,951:
R(49081) is probably prime.
</pre>
 
=={{header|Scala}}==
{{trans|Java}}
<langsyntaxhighlight lang="scala">object CircularPrimes {
def main(args: Array[String]): Unit = {
println("First 19 circular primes:")
Line 2,340 ⟶ 3,060:
BigInt.apply(new String(ch))
}
}</langsyntaxhighlight>
{{out}}
<pre>First 19 circular primes:
Line 2,350 ⟶ 3,070:
R(15073) is not prime.
R(25031) is not prime.</pre>
 
=={{header|Sidef}}==
{{trans|Raku}}
<langsyntaxhighlight lang="ruby">func is_circular_prime(n) {
n.is_prime || return false
 
Line 2,381 ⟶ 3,100:
say ("R(#{n}) -> ", is_prob_prime((10**n - 1)/9) ? 'probably prime' : 'composite',
" (took: #{'%.3f' % Time.micro-now} sec)")
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,400 ⟶ 3,119:
R(35317) -> composite (took: 0.875 sec)
</pre>
 
=={{header|Wren}}==
{{trans|Go}}
Line 2,406 ⟶ 3,124:
{{libheader|Wren-big}}
{{libheader|Wren-fmt}}
{{libheader|Wren-str}}
===Wren-cli===
Second part is very slow - over 37 minutes to find all four.
<langsyntaxhighlight ecmascriptlang="wren">import "./math" for Int
import "./big" for BigInt
import "./str" for Str
var circs = []
Line 2,431 ⟶ 3,151:
return true
}
 
var repunit = Fn.new { |n| BigInt.new(Str.repeat("1" *, n)) }
System.print("The first 19 circular primes are:")
Line 2,461 ⟶ 3,181:
}
System.print(circs)
 
System.print("\nThe next 4 circular primes, in repunit format, are:")
count = 0
Line 2,473 ⟶ 3,193:
}
}
System.print(rus)</langsyntaxhighlight>
 
{{out}}
Line 2,484 ⟶ 3,204:
</pre>
<br>
 
===Embedded===
{{libheader|GMPWren-gmp}}
A massive speed-up, of course, when GMP is plugged in for the 'probably prime' calculations. Around 11.5 minutes 19 seconds including the stretch goal.
<langsyntaxhighlight ecmascriptlang="wren">/* circular_primes_embeddedCircular_primes_embedded.wren */
 
import "./gmp" for Mpz
import "./math" for Int
import "./fmt" for Fmt
import "./str" for Str
 
foreign class Mpz {
construct init() {}
 
foreign setString(str, base)
 
foreign probPrime(reps)
}
 
var circs = []
Line 2,520 ⟶ 3,235:
return true
}
 
System.print("The first 19 circular primes are:")
var digits = [1, 3, 7, 9]
Line 2,548 ⟶ 3,263:
}
System.print(circs)
 
System.print("\nThe next 4 circular primes, in repunit format, are:")
count = 0
var rus = []
var primes = Int.primeSieve(10000)
var repunit = Mpz.initnew()
for (p in primes[3..-1]) {
repunit.setStringsetStr(Str.repeat("1" *, p), 10)
if (repunit.probPrime(10) > 0) {
rus.add("R(%(p))")
Line 2,565 ⟶ 3,280:
System.print("\nThe following repunits are probably circular primes:")
for (i in [5003, 9887, 15073, 25031, 35317, 49081]) {
repunit.setStringsetStr(Str.repeat("1" *, i), 10)
Fmt.print("R($-5d) : $s", i, repunit.probPrime(15) > 0)
}</langsyntaxhighlight>
<br>
and the C program to embed the above script in:
<lang c>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gmp.h>
#include "wren.h"
 
/* C <=> Wren interface functions */
 
void C_mpzAllocate(WrenVM* vm) {
mpz_t *pz = (mpz_t*)wrenSetSlotNewForeign(vm, 0, 0, sizeof(mpz_t));
mpz_init(*pz);
}
 
void C_setString(WrenVM* vm) {
mpz_t *pz = (mpz_t*)wrenGetSlotForeign(vm, 0);
const char *str = wrenGetSlotString(vm, 1);
int base = (int)wrenGetSlotDouble(vm, 2);
mpz_set_str(*pz, str, base);
}
 
void C_probPrime(WrenVM* vm) {
mpz_t *pz = (mpz_t*)wrenGetSlotForeign(vm, 0);
int reps = (int)wrenGetSlotDouble(vm, 1);
int ret = mpz_probab_prime_p(*pz, reps);
wrenSetSlotDouble(vm, 0, (double)ret);
}
 
WrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {
WrenForeignClassMethods methods;
methods.allocate = NULL;
methods.finalize = NULL;
if (strcmp(module, "main") == 0) {
if (strcmp(className, "Mpz") == 0) {
methods.allocate = C_mpzAllocate;
}
}
return methods;
}
 
WrenForeignMethodFn bindForeignMethod(
WrenVM* vm,
const char* module,
const char* className,
bool isStatic,
const char* signature) {
if (strcmp(module, "main") == 0) {
if (strcmp(className, "Mpz") == 0) {
if (!isStatic && strcmp(signature, "setString(_,_)") == 0) return C_setString;
if (!isStatic && strcmp(signature, "probPrime(_)") == 0) return C_probPrime;
}
}
return NULL;
}
 
static void writeFn(WrenVM* vm, const char* text) {
printf("%s", text);
}
 
void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {
switch (errorType) {
case WREN_ERROR_COMPILE:
printf("[%s line %d] [Error] %s\n", module, line, msg);
break;
case WREN_ERROR_STACK_TRACE:
printf("[%s line %d] in %s\n", module, line, msg);
break;
case WREN_ERROR_RUNTIME:
printf("[Runtime Error] %s\n", msg);
break;
}
}
 
char *readFile(const char *fileName) {
FILE *f = fopen(fileName, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
rewind(f);
char *script = malloc(fsize + 1);
fread(script, 1, fsize, f);
fclose(f);
script[fsize] = 0;
return script;
}
 
static void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {
if( result.source) free((void*)result.source);
}
 
WrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {
WrenLoadModuleResult result = {0};
if (strcmp(name, "random") != 0 && strcmp(name, "meta") != 0) {
result.onComplete = loadModuleComplete;
char fullName[strlen(name) + 6];
strcpy(fullName, name);
strcat(fullName, ".wren");
result.source = readFile(fullName);
}
return result;
}
 
int main(int argc, char **argv) {
WrenConfiguration config;
wrenInitConfiguration(&config);
config.writeFn = &writeFn;
config.errorFn = &errorFn;
config.bindForeignClassFn = &bindForeignClass;
config.bindForeignMethodFn = &bindForeignMethod;
config.loadModuleFn = &loadModule;
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "circular_primes_embedded.wren";
char *script = readFile(fileName);
WrenInterpretResult result = wrenInterpret(vm, module, script);
switch (result) {
case WREN_RESULT_COMPILE_ERROR:
printf("Compile Error!\n");
break;
case WREN_RESULT_RUNTIME_ERROR:
printf("Runtime Error!\n");
break;
case WREN_RESULT_SUCCESS:
break;
}
wrenFreeVM(vm);
free(script);
return 0;
}</lang>
 
{{out}}
Line 2,715 ⟶ 3,302:
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">func IsPrime(N); \Return 'true' if N > 2 is a prime number
int N, I;
[if (N&1) = 0 \even number\ then return false;
for I:= 3 to sqrt(N) do
[if rem(N/I) = 0 then return false;
I:= I+1;
];
return true;
];
 
func CircPrime(N0); \Return 'true' if N0 is a circular prime
int N0, N, Digits, Rotation, I, R;
[N:= N0;
Digits:= 0; \count number of digits in N
repeat Digits:= Digits+1;
N:= N/10;
until N = 0;
N:= N0;
for Rotation:= 0 to Digits-1 do
[if not IsPrime(N) then return false;
N:= N/10; \rotate least sig digit into high end
R:= rem(0);
for I:= 0 to Digits-2 do
R:= R*10;
N:= N+R;
if N0 > N then \reject N0 if it has a smaller prime rotation
return false;
];
return true;
];
 
int Counter, N;
[IntOut(0, 2); ChOut(0, ^ ); \show first circular prime
Counter:= 1;
N:= 3; \remaining primes are odd
loop [if CircPrime(N) then
[IntOut(0, N); ChOut(0, ^ );
Counter:= Counter+1;
if Counter >= 19 then quit;
];
N:= N+2;
];
]</syntaxhighlight>
 
{{out}}
<pre>
2 3 5 7 11 13 17 37 79 113 197 199 337 1193 3779 11939 19937 193939 199933
</pre>
=={{header|Zig}}==
{{works with|Zig|0.11.0}}
As of now (Zig release 0.8.1), Zig has large integer support, but there is not yet a prime test in the standard library. Therefore, we only find the circular primes < 1e6. As with the Prolog version, we only check numbers composed of 1, 3, 7, or 9.
Zig has large integer support, but there is not yet a prime test in the standard library. Therefore, we only find the circular primes < 1e6. As with the Prolog version, we only check numbers composed of 1, 3, 7, or 9.
<lang Zig>
<syntaxhighlight lang="zig">
const std = @import("std");
const math = std.math;
const heap = std.heap;
const stdout = std.io.getStdOut().writer();
 
pub fn main() !void {
Line 2,727 ⟶ 3,363:
defer arena.deinit();
 
varconst candidatesallocator = std.PriorityQueue(u32).init(&arena.allocator, u32cmp();
 
var candidates = std.PriorityQueue(u32, void, u32cmp).init(allocator, {});
defer candidates.deinit();
 
const stdout = std.io.getStdOut().writer();
 
try stdout.print("The circular primes are:\n", .{});
Line 2,753 ⟶ 3,393:
}
 
fn u32cmp(_: void, a: u32, b: u32) math.Order {
return math.order(a, b);
}
 
fn circular(n0: u32) bool {
if (!isprimeisPrime(n0))
return false
else {
var n = n0;
var d: u32 = @floatToIntintFromFloat(u32, @log10(@intToFloatas(f32, @floatFromInt(n))));
return while (d > 0) : (d -= 1) {
n = rotate(n);
if (n < n0 or !isprimeisPrime(n))
break false;
} else true;
Line 2,775 ⟶ 3,415:
return 0
else {
const d: u32 = @floatToIntintFromFloat(u32, @log10(@intToFloatas(f32, @floatFromInt(n)))); // digit count - 1
const m = math.pow(u32, 10, d);
return (n % m) * 10 + n / m;
Line 2,781 ⟶ 3,421:
}
 
fn isprimeisPrime(n: u32) bool {
if (n < 2)
return false;
Line 2,802 ⟶ 3,442:
} else true;
}
</syntaxhighlight>
</lang>
{{Out}}
<pre>
9,476

edits