Long primes: Difference between revisions

42,059 bytes added ,  4 months ago
Added Algol 68
m (→‎{{header|C sharp}}: simplified SomePrimeGenerator.Primes slightly)
(Added Algol 68)
 
(48 intermediate revisions by 20 users not shown)
Line 2:
 
 
A   '''long prime'''   (theas definitiondefined thathere) will  beis useda prime number whose reciprocal   (in decimal)   has
here)a   are''period primes whose reciprocalslength''   (inof decimal)one  less than the prime havenumber.
a   ''period length''   of one less than
the prime number   (also expressed in decimal).
 
 
Line 16 ⟶ 14:
:::*   proper primes
 
 
Another definition:   primes   '''p'''   such that the decimal expansion of   '''1/p'''   has period   '''p-1''',   which is the greatest period possible for any integer.
 
 
Line 51:
:*   [[oeis:A001913|OEIS: A001913]]
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">F sieve(limit)
[Int] primes
V c = [0B] * (limit + 1)
V p = 3
L
V p2 = p * p
I p2 > limit
L.break
L(i) (p2 .< limit).step(2 * p)
c[i] = 1B
L
p += 2
I !c[p]
L.break
 
L(i) (3 .< limit).step(2)
I !(c[i])
primes.append(i)
R primes
 
F findPeriod(n)
V r = 1
L(i) 1 .< n
r = (10 * r) % n
V rr = r
V period = 0
L
r = (10 * r) % n
period++
I r == rr
L.break
R period
 
V primes = sieve(64000)
[Int] longPrimes
L(prime) primes
I findPeriod(prime) == prime - 1
longPrimes.append(prime)
V numbers = [500, 1000, 2000, 4000, 8000, 16000, 32000, 64000]
V count = 0
V index = 0
V totals = [0] * numbers.len
L(longPrime) longPrimes
I longPrime > numbers[index]
totals[index] = count
index++
count++
totals.last = count
print(‘The long primes up to 500 are:’)
print(String(longPrimes[0 .< totals[0]]).replace(‘,’, ‘’))
print("\nThe number of long primes up to:")
L(total) totals
print(‘ #5 is #.’.format(numbers[L.index], total))</syntaxhighlight>
 
{{out}}
<pre>
The long primes up to 500 are:
[7 17 19 23 29 47 59 61 97 109 113 131 149 167 179 181 193 223 229 233 257 263 269 313 337 367 379 383 389 419 433 461 487 491 499]
 
The number of long primes up to:
500 is 35
1000 is 60
2000 is 116
4000 is 218
8000 is 390
16000 is 716
32000 is 1300
64000 is 2430
</pre>
 
=={{header|ALGOL 68}}==
The PERIOD operator is translated from the C sample's find_period routine.
<syntaxhighlight lang="algol68">
BEGIN # find some long primes - primes whose reciprocol have a period of p-1 #
INT max number = 64 000;
# sieve the primes to max number #
[ 1 : max number ]BOOL is prime; FOR i TO UPB is prime DO is prime[ i ] := ODD i OD;
is prime[ 1 ] := FALSE;
is prime[ 2 ] := TRUE;
FOR s FROM 3 BY 2 TO ENTIER sqrt( max number ) DO
IF is prime[ s ] THEN
FOR p FROM s * s BY s TO UPB is prime DO is prime[ p ] := FALSE OD
FI
OD;
 
OP PERIOD = ( INT n )INT: # returns the period of the reciprocal of n #
BEGIN
INT r := 1;
FOR i TO n + 1 DO
r *:= 10 MODAB n
OD;
INT rr = r;
INT period := 0;
WHILE r *:= 10 MODAB n;
period +:= 1;
r /= rr
DO SKIP OD;
period
END # PERIOD # ;
 
print( ( "Long primes upto 500:", newline, " " ) );
INT lp count := 0;
FOR p FROM 3 TO 500 DO
IF is prime[ p ] THEN
IF PERIOD p = p - 1 THEN
print( ( " ", whole( p, 0 ) ) );
lp count +:= 1
FI
FI
OD;
print( ( newline ) );
INT limit := 500;
FOR p FROM 500 WHILE limit <= 64 000 DO
IF p = limit THEN
print( ( "Long primes up to: ", whole( p, -5 ), ": ", whole( lp count, 0 ), newline ) );
limit *:= 2
FI;
IF is prime[ p ] THEN
IF PERIOD p = p - 1 THEN
lp count +:= 1
FI
FI
OD
 
END
</syntaxhighlight>
{{out}}
<pre>
Long primes upto 500:
7 17 19 23 29 47 59 61 97 109 113 131 149 167 179 181 193 223 229 233 257 263 269 313 337 367 379 383 389 419 433 461 487 491 499
Long primes up to: 500: 35
Long primes up to: 1000: 60
Long primes up to: 2000: 116
Long primes up to: 4000: 218
Long primes up to: 8000: 390
Long primes up to: 16000: 716
Long primes up to: 32000: 1300
Long primes up to: 64000: 2430
</pre>
 
=={{header|AppleScript}}==
The isLongPrime(n) handler here is a translation of the faster [https://www.rosettacode.org/wiki/Long_primes#Phix Phix] one.
 
<syntaxhighlight lang="applescript">on sieveOfEratosthenes(limit)
script o
property numberList : {missing value}
end script
repeat with n from 2 to limit
set end of o's numberList to n
end repeat
repeat with n from 2 to (limit ^ 0.5 div 1)
if (item n of o's numberList is n) then
repeat with multiple from (n * n) to limit by n
set item multiple of o's numberList to missing value
end repeat
end if
end repeat
return o's numberList's numbers
end sieveOfEratosthenes
 
on factors(n)
set output to {}
if (n < 0) then set n to -n
set sqrt to n ^ 0.5
set limit to sqrt div 1
if (limit = sqrt) then
set end of output to limit
set limit to limit - 1
end if
repeat with i from limit to 1 by -1
if (n mod i is 0) then
set beginning of output to i
set end of output to n div i
end if
end repeat
return output
end factors
 
on isLongPrime(n)
if (n < 3) then return false
script o
property f : factors(n - 1)
end script
set counter to 0
repeat with fi in o's f
set fi to fi's contents
set e to 1
set base to 10
repeat until (fi = 0)
if (fi mod 2 = 1) then set e to e * base mod n
set base to base * base mod n
set fi to fi div 2
end repeat
if (e = 1) then
set counter to counter + 1
if (counter > 1) then exit repeat
end if
end repeat
return (counter = 1)
end isLongPrime
 
-- Task code:
on longPrimesTask()
script o
-- The isLongPrime() handler above returns the correct result for any number
-- passed to it, but feeeding it only primes in the first place speeds things up.
property primes : sieveOfEratosthenes(64000)
property longs : {}
end script
set output to {}
set counter to 0
set mileposts to {500, 1000, 2000, 4000, 8000, 16000, 32000, 64000}
set m to 1
set nextMilepost to beginning of mileposts
set astid to AppleScript's text item delimiters
repeat with p in o's primes
set p to p's contents
if (isLongPrime(p)) then
-- p being odd, it's never exactly one of the even mileposts.
if (p < 500) then
set end of o's longs to p
else if (p > nextMilepost) then
if (nextMilepost = 500) then
set AppleScript's text item delimiters to space
set end of output to "Long primes up to 500:"
set end of output to o's longs as text
end if
set end of output to "Number of long primes up to " & nextMilepost & ": " & counter
set m to m + 1
set nextMilepost to item m of mileposts
end if
set counter to counter + 1
end if
end repeat
set end of output to "Number of long primes up to " & nextMilepost & ": " & counter
set AppleScript's text item delimiters to linefeed
set output to output as text
set AppleScript's text item delimiters to astid
return output
end longPrimesTask
 
longPrimesTask()</syntaxhighlight>
 
{{output}}
<pre>"Long primes up to 500:
7 17 19 23 29 47 59 61 97 109 113 131 149 167 179 181 193 223 229 233 257 263 269 313 337 367 379 383 389 419 433 461 487 491 499
Number of long primes up to 500: 35
Number of long primes up to 1000: 60
Number of long primes up to 2000: 116
Number of long primes up to 4000: 218
Number of long primes up to 8000: 390
Number of long primes up to 16000: 716
Number of long primes up to 32000: 1300
Number of long primes up to 64000: 2430"</pre>
 
=={{header|C}}==
{{trans|Go}}
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
Line 134 ⟶ 400:
free(primes);
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 154 ⟶ 420:
=={{header|C sharp}}==
{{works with|C sharp|7}}
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 196 ⟶ 462:
for (; j<= lim; j++) if (!flags[j]) yield return j;
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 211 ⟶ 477:
=={{header|C++}}==
{{trans|C}}
<langsyntaxhighlight lang="cpp">
#include <iomanip>
#include <iostream>
Line 298 ⟶ 564:
delete [] totals;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 316 ⟶ 582:
64000 is 2430
</pre>
 
=={{header|Common Lisp}}==
{{trans|Raku}}
<syntaxhighlight lang="lisp">; Primality test using the Sieve of Eratosthenes with a couple minor optimizations
(defun primep (n)
(cond ((and (<= n 3) (> n 1)) t)
((some #'zerop (mapcar (lambda (d) (mod n d)) '(2 3))) nil)
(t (loop for i = 5 then (+ i 6)
while (<= (* i i) n)
when (some #'zerop (mapcar (lambda (d) (mod n (+ i d))) '(0 2))) return nil
finally (return t)))))
 
; Translation of the long-prime algorithm from the Raku solution
(defun long-prime-p (n)
(cond
((< n 3) nil)
((not (primep n)) nil)
(t (let* ((rr (loop repeat (1+ n)
for r = 1 then (mod (* 10 r) n)
finally (return r)))
 
(period (loop for p = 0 then (1+ p)
for r = (mod (* 10 rr) n) then (mod (* 10 r) n)
while (and (< p n) (/= r rr))
finally (return (1+ p)))))
 
(= period (1- n))))))
 
(format t "~{~a~^, ~}" (loop for n from 1 to 500 if (long-prime-p n) collect n))
</syntaxhighlight>
{{Out}}
<pre>7, 17, 19, 23, 29, 47, 59, 61, 97, 109, 113, 131, 149, 167, 179, 181, 193, 223, 229, 233, 257, 263, 269, 313, 337, 367, 379, 383, 389, 419, 433, 461, 487, 491, 499</pre>
 
=={{header|Crystal}}==
{{trans|Sidef}}
Simpler but slower.
<langsyntaxhighlight lang="ruby">require "big"
 
def prime?(n) # P3 Prime Generator primality test
Line 350 ⟶ 648:
puts "Number of long primes ≤ #{n}: #{(7..n).count { |pc| long_prime? pc }}"
end
puts "\nTime: #{(Time.monotonic - start).total_seconds} secs"</langsyntaxhighlight>
 
{{out}}
Line 370 ⟶ 668:
 
Faster: using divisors of (p - 1) and powmod().
<langsyntaxhighlight lang="ruby">require "big"
 
def prime?(n) # P3 Prime Generator primality test
Line 415 ⟶ 713:
puts "Number of long primes ≤ #{n}: #{(7..n).count { |pc| long_prime? pc }}"
end
puts "\nTime: #{(Time.monotonic - start).total_seconds} secs"</langsyntaxhighlight>
{{out}}
<pre>
Line 432 ⟶ 730:
Run as: $ crystal run longprimes.cr --release
Time: 0.28927228 secs
 
=={{header|Delphi}}==
See [https://rosettacode.org/wiki/Long_primes#Pascal Pascal].
 
 
=={{header|EasyLang}}==
<syntaxhighlight>
fastfunc isprim num .
if num mod 2 = 0 and num > 2
return 0
.
i = 3
while i <= sqrt num
if num mod i = 0
return 0
.
i += 2
.
return 1
.
prim = 2
proc nextprim . .
repeat
prim += 1
until isprim prim = 1
.
.
func period n .
r = 1
repeat
r = (r * 10) mod n
p += 1
until r <= 1
.
return p
.
#
print "Long primes up to 500 are:"
repeat
nextprim
until prim > 500
if period prim = prim - 1
write prim & " "
cnt += 1
.
.
print ""
print ""
print "The number of long primes up to:"
limit = 500
repeat
if prim > limit
print limit & " is " & cnt
limit *= 2
.
until limit > 32000
if period prim = prim - 1
cnt += 1
.
nextprim
.
</syntaxhighlight>
 
=={{header|F_Sharp|F#}}==
Line 437 ⟶ 797:
This task uses [http://www.rosettacode.org/wiki/Extensible_prime_generator#The_function Extensible Prime Generator (F#)]<br>
This task uses [[Factors_of_an_integer#F.23]]
<langsyntaxhighlight lang="fsharp">
// Return true if prime n is a long prime. Nigel Galloway: September 25th., 2018
let fN n g = let rec fN i g e l = match e with | 0UL -> i
Line 444 ⟶ 804:
fN 1UL 10UL (uint64 g) (uint64 n)
let isLongPrime n=Seq.length (factors (n-1) |> Seq.filter(fun g->(fN n g)=1UL))=1
</syntaxhighlight>
</lang>
===The Task===
<langsyntaxhighlight lang="fsharp">
primes |> Seq.skip 3 |> Seq.takeWhile(fun n->n<500) |> Seq.filter isLongPrime |> Seq.iter(printf "%d ")
</syntaxhighlight>
</lang>
{{out}}
<pre>
7 17 19 23 29 47 59 61 97 109 113 131 149 167 179 181 193 223 229 233 257 263 269 313 337 367 379 383 389 419 433 461 487 491 499
</pre>
<langsyntaxhighlight lang="fsharp">
printfn "There are %d long primes less than 500" (primes |> Seq.skip 3 |> Seq.takeWhile(fun n->n<500) |> Seq.filter isLongPrime |> Seq.length)
</syntaxhighlight>
</lang>
{{out}}
<pre>
There are 35 long primes less than 500
</pre>
<langsyntaxhighlight lang="fsharp">
printfn "There are %d long primes less than 1000" (primes |> Seq.skip 3 |> Seq.takeWhile(fun n->n<1000) |> Seq.filter isLongPrime |> Seq.length)
</syntaxhighlight>
</lang>
{{out}}
<pre>
There are 60 long primes less than 1000
</pre>
<langsyntaxhighlight lang="fsharp">
printfn "There are %d long primes less than 2000" (primes |> Seq.skip 3 |> Seq.takeWhile(fun n->n<2000) |> Seq.filter isLongPrime |> Seq.length)
</syntaxhighlight>
</lang>
{{out}}
<pre>
There are 116 long primes less than 2000
</pre>
<langsyntaxhighlight lang="fsharp">
printfn "There are %d long primes less than 4000" (primes |> Seq.skip 3 |> Seq.takeWhile(fun n->n<4000) |> Seq.filter isLongPrime|> Seq.length)
</syntaxhighlight>
</lang>
{{out}}
<pre>
There are 218 long primes less than 4000
</pre>
<langsyntaxhighlight lang="fsharp">
printfn "There are %d long primes less than 8000" (primes |> Seq.skip 3 |> Seq.takeWhile(fun n->n<8000) |> Seq.filter isLongPrime |> Seq.length)
</syntaxhighlight>
</lang>
{{out}}
<pre>
There are 390 long primes less than 8000
</pre>
<langsyntaxhighlight lang="fsharp">
printfn "There are %d long primes less than 16000" (primes |> Seq.skip 3 |> Seq.takeWhile(fun n->n<16000) |> Seq.filter isLongPrime |> Seq.length)
</syntaxhighlight>
</lang>
{{out}}
<pre>
There are 716 long primes less than 16000
</pre>
<langsyntaxhighlight lang="fsharp">
printfn "There are %d long primes less than 32000" (primes |> Seq.skip 3 |> Seq.takeWhile(fun n->n<32000) |> Seq.filter isLongPrime |> Seq.length)
</syntaxhighlight>
</lang>
{{out}}
<pre>
There are 1300 long primes less than 32000
</pre>
<langsyntaxhighlight lang="fsharp">
printfn "There are %d long primes less than 64000" (primes |> Seq.skip 3 |> Seq.takeWhile(fun n->n<64000) |> Seq.filter isLongPrime|> Seq.length)
</syntaxhighlight>
</lang>
{{out}}
<pre>
There are 2430 long primes less than 64000
</pre>
<langsyntaxhighlight lang="fsharp">
printfn "There are %d long primes less than 128000" (primes |> Seq.skip 3 |> Seq.takeWhile(fun n->n<128000) |> Seq.filter isLongPrime|> Seq.length)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 517 ⟶ 877:
Real: 00:00:01.294, CPU: 00:00:01.300, GC gen0: 27, gen1: 0
</pre>
<langsyntaxhighlight lang="fsharp">
printfn "There are %d long primes less than 256000" (primes |> Seq.skip 3 |> Seq.takeWhile(fun n->n<256000) |> Seq.filter isLongPrime|> Seq.length)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 525 ⟶ 885:
Real: 00:00:03.434, CPU: 00:00:03.440, GC gen0: 58, gen1: 0
</pre>
<langsyntaxhighlight lang="fsharp">
printfn "There are %d long primes less than 512000" (primes |> Seq.skip 3 |> Seq.takeWhile(fun n->n<512000) |> Seq.filter isLongPrime|> Seq.length)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 533 ⟶ 893:
Real: 00:00:09.248, CPU: 00:00:09.260, GC gen0: 128, gen1: 0
</pre>
<langsyntaxhighlight lang="fsharp">
printfn "There are %d long primes less than 1024000" (primes |> Seq.skip 3 |> Seq.takeWhile(fun n->n<1024000) |> Seq.filter isLongPrime|> Seq.length)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 543 ⟶ 903:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: formatting fry io kernel math math.functions math.primes
math.primes.factors memoize prettyprint sequences ;
IN: rosetta-code.long-primes
Line 565 ⟶ 925:
[ .#lp<=n ] each ;
 
MAIN: long-primes-demo</langsyntaxhighlight>
{{out}}
<pre>
Line 579 ⟶ 939:
1300 long primes <= 32000
2430 long primes <= 64000
</pre>
 
=={{header|Forth}}==
{{works with|Gforth}}
The prime sieve code was borrowed from [[Sieve of Eratosthenes#Forth]].
<syntaxhighlight lang="forth">: prime? ( n -- ? ) here + c@ 0= ;
: notprime! ( n -- ) here + 1 swap c! ;
 
: sieve ( n -- )
here over erase
0 notprime!
1 notprime!
2
begin
2dup dup * >
while
dup prime? if
2dup dup * do
i notprime!
dup +loop
then
1+
repeat
2drop ;
 
: modpow { c b a -- a^b mod c }
c 1 = if 0 exit then
1
a c mod to a
begin
b 0>
while
b 1 and 1 = if
a * c mod
then
a a * c mod to a
b 2/ to b
repeat ;
 
: divide_out ( n1 n2 -- n )
begin
2dup mod 0=
while
tuck / swap
repeat drop ;
 
: long_prime? ( n -- ? )
dup prime? invert if drop false exit then
10 over mod 0= if drop false exit then
dup 1-
2 >r
begin
over r@ dup * >
while
r@ prime? if
dup r@ mod 0= if
over dup 1- r@ / 10 modpow 1 = if
2drop rdrop false exit
then
r@ divide_out
then
then
r> 1+ >r
repeat
rdrop
dup 1 = if 2drop true exit then
over 1- swap / 10 modpow 1 <> ;
 
: next_long_prime ( n -- n )
begin 2 + dup long_prime? until ;
 
500 constant limit1
512000 constant limit2
 
: main
limit2 1+ sieve
limit2 limit1 3
0 >r
." Long primes up to " over 1 .r ." :" cr
begin
2 pick over >
while
next_long_prime
dup limit1 < if dup . then
dup 2 pick > if
over limit1 = if cr then
." Number of long primes up to " over 6 .r ." : " r@ 5 .r cr
swap 2* swap
then
r> 1+ >r
repeat
2drop drop rdrop ;
 
main
bye</syntaxhighlight>
 
{{out}}
Execution time is about 1.1 seconds on my machine (3.2GHz Quad-Core Intel Core i5).
<pre>
Long primes up to 500:
7 17 19 23 29 47 59 61 97 109 113 131 149 167 179 181 193 223 229 233 257 263 269 313 337 367 379 383 389 419 433 461 487 491 499
Number of long primes up to 500: 35
Number of long primes up to 1000: 60
Number of long primes up to 2000: 116
Number of long primes up to 4000: 218
Number of long primes up to 8000: 390
Number of long primes up to 16000: 716
Number of long primes up to 32000: 1300
Number of long primes up to 64000: 2430
Number of long primes up to 128000: 4498
Number of long primes up to 256000: 8434
Number of long primes up to 512000: 15920
</pre>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' version 01-02-2019
' compile with: fbc -s console
 
Line 656 ⟶ 1,128:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>Long primes upto 500 are 7 17 19 23 29 47 59 61 97 109 113 131 149 167 179 181 193 223 229 233 257 263 269 313 337 367 379 383 389 419 433 461 487 491 499
Line 670 ⟶ 1,142:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
import "fmt"
Line 739 ⟶ 1,211:
fmt.Printf(" %5d is %d\n", numbers[i], total)
}
}</langsyntaxhighlight>
 
{{out}}
Line 757 ⟶ 1,229:
</pre>
=={{header|Haskell}}==
<syntaxhighlight lang="haskell">import Data.List (elemIndex)
<lang Haskell>
import Data.List
 
longPrimesUpTo :: Int -> [Int]
longPrimesUpTo n = filter isLongPrime $ takeWhile (<n) primes
filter isLongPrime $
where sieve (p:xs) = p : sieve [x | x <- xs, x `mod` p /= 0]
takeWhile (< n) primes = sieve [2..]
where
isLongPrime n = found
sieve (p : xs) = p where: cyclessieve =[x take| n (iterate (\yx <-> 10xs, * yx `mod` n)p 1)/= 0]
primes = sieve [2 ..]
index = findIndex (== head cycles) $ tail cycles
isLongPrime n = found
found = case index of (Just i) -> n - i == 2
where
_ -> False
cycles = take n (iterate ((`mod` n) . (10 *)) 1)
index = elemIndex (head cycles) $ tail cycles
found = case index of
(Just i) -> n - i == 2
_ -> False
 
display :: Int -> IO ()
display n = if n <= 64000 then do
if n <= 64000
putStrLn (show n ++ " is " ++ show (length $ longPrimesUpTo n))
then do
display (n * 2)
else pure ()putStrLn
( show n <> " is "
<> show (length $ longPrimesUpTo n)
)
display (n * 2)
else pure ()
 
main :: IO ()
main = do
let fiveHundred = longPrimesUpTo 500
putStrLn
putStrLn ("The long primes up to 35 are:\n" ++ show fiveHundred ++ "\n")
( "The long primes up to 35 are:\n"
putStrLn ("500 is " ++ show (length fiveHundred))
<> show fiveHundred
display 1000
<> "\n"
</lang>
)
putStrLn ("500 is " <> show (length fiveHundred))
display 1000</syntaxhighlight>
{{out}}
<pre>The long primes up to 35 are:
<pre>
The long primes up to 35 are:
[7,17,19,23,29,47,59,61,97,109,113,131,149,167,179,181,193,223,229,233,257,263,269,313,337,367,379,383,389,419,433,461,487,491,499]
 
Line 795 ⟶ 1,278:
16000 is 716
32000 is 1300
64000 is 2430</pre>
</pre>
 
=={{header|J}}==
Line 846 ⟶ 1,328:
=={{header|Java}}==
{{trans|C}}
<langsyntaxhighlight lang="java">
import java.util.LinkedList;
import java.util.List;
Line 916 ⟶ 1,398:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 931 ⟶ 1,413:
32000 is 1300
64000 is 2430
</pre>
 
=={{header|jq}}==
'''Adapted from [[#Wren|Wren]]'''
{{works with|jq}}
'''Works with gojq, the Go implementation of jq''' (*)
 
This entry does not attempt to avoid the redundancy involved in the subtasks, but instead
includes a prime number generator intended for efficiently generating large numbers of primes.
 
(*) For the computationally intensive subtasks, gojq will require too much memory.
 
'''Preliminaries'''
<syntaxhighlight lang="jq">
def count(s): reduce s as $x (0; .+1);
 
# Is the input integer a prime?
# "previous" should be a sorted array of consecutive primes
# from 2 on that includes the greatest prime less than (.|sqrt)
def is_prime(previous):
. as $in
| (($in + 1) | sqrt) as $sqrt
| first(previous[]
| if . > $sqrt then 1
elif 0 == ($in % .) then 0
else empty
end) // 1
| . == 1;
 
# This assumes . is an array of consecutive primes beginning with [2,3]
def next_prime:
. as $previous
| (2 + .[-1] )
| until(is_prime($previous); . + 2) ;
 
# Emit primes from 2 up
def primes:
# The helper function has arity 0 for TCO
# It expects its input to be an array of previously found primes, in order:
def next:
. as $previous
| ($previous|next_prime) as $next
| $next, (($previous + [$next]) | next) ;
2, 3, ([2,3] | next);
 
</syntaxhighlight>
'''Long Primes'''
<syntaxhighlight lang="jq">
# finds the period of the reciprocal of .
# (The following definition does not make a special case of 2
# but yields a justifiable result for 2, namely 1.)
def findPeriod:
. as $n
| (reduce range(1; $n+2) as $i (1; (. * 10) % $n)) as $rr
| {r: $rr, period:0, ok:true}
| until( .ok|not;
.r = (10 * .r) % $n
| .period += 1
| .ok = (.r != $rr) )
| .period ;
 
# This definition takes into account the
# claim in the preamble that the first long prime is 7:
def long_primes_less_than($n):
label $out
| primes
| if . >= $n then break $out else . end
| select(. > 2 and (findPeriod == . - 1));
 
def count_long_primes:
count(long_primes_less_than(.));
 
# Since 2 is not a "long prime" for the purposes of this
# article, we can begin searching at 3:
"Long primes ≤ 500: ", long_primes_less_than(500),
 
"\n",
 
(500,1000, 2000, 4000, 8000, 16000, 32000, 64000
| "Number of long primes ≤ \(.): \(count_long_primes)" )
 
</syntaxhighlight>
{{out}}
<pre>
Long primes ≤ 500:
7
17
19
23
29
47
59
61
97
109
113
131
149
167
179
181
193
223
229
233
257
263
269
313
337
367
379
383
389
419
433
461
487
491
499
 
Number of long primes ≤ 500: 35
Number of long primes ≤ 1000: 60
Number of long primes ≤ 2000: 116
Number of long primes ≤ 4000: 218
Number of long primes ≤ 8000: 390
Number of long primes ≤ 16000: 716
Number of long primes ≤ 32000: 1300
Number of long primes ≤ 64000: 2430
</pre>
 
=={{header|Julia}}==
{{trans|Sidef}}
<langsyntaxhighlight lang="julia">
using Primes
 
Line 966 ⟶ 1,577:
println("Number of long primes ≤ $i: $(sum(map(x->islongprime(x), 1:i)))")
end
</syntaxhighlight>
</lang>
{{output}}<pre>
Long primes ≤ 500:
Line 984 ⟶ 1,595:
=={{header|Kotlin}}==
{{trans|Go}}
<langsyntaxhighlight lang="scala">// Version 1.2.60
fun sieve(limit: Int): List<Int> {
Line 1,044 ⟶ 1,655:
System.out.printf(" %5d is %d\n", numbers[i], total)
}
}</langsyntaxhighlight>
 
{{output}}
Line 1,066 ⟶ 1,677:
Sieve leave to stack of values primes. This happen because we call the function as a module, so we pass the current stack (modules call modules passing own stack of values). We can place value to stack using Push to the top (as LIFO) or using Data to bottom (as FIFO). Variable Number read a number from stack and drop it.
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module LongPrimes {
Sieve=lambda (limit)->{
Line 1,136 ⟶ 1,747:
}
LongPrimes
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,155 ⟶ 1,766:
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">
<lang Maple>
with(NumberTheory):
with(ArrayTools):
Line 1,190 ⟶ 1,801:
numOfLongPrimes;
 
</syntaxhighlight>
</lang>
{{out}}<pre>
[7, 17, 19, 23, 29, 47, 59, 61, 97, 109, 113, 131, 149, 167, 179, 181, 193,
Line 1,201 ⟶ 1,812:
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">lPrimes[n_] := Select[Range[2, n], Length[RealDigits[1/#][[1, 1]]] == # - 1 &];
lPrimes[500]
Length /@ lPrimes /@ ( 250*2^Range[8])</langsyntaxhighlight>
{{out}}
<pre>{7, 17, 19, 23, 29, 47, 59, 61, 97, 109, 113, 131, 149, 167, 179,
Line 1,211 ⟶ 1,822:
 
{35, 60, 116, 218, 390, 716, 1300, 2430}
</pre>
 
=={{header|Maxima}}==
<syntaxhighlight lang="maxima">
/* Test cases */
/* Long primes up to 500 */
sublist(makelist(i,i,500),lambda([x],primep(x) and zn_order(10,x)=x-1));
 
/* Number of long primes up to a specified limit */
length(sublist(makelist(i,i,500),lambda([x],primep(x) and zn_order(10,x)=x-1)));
length(sublist(makelist(i,i,1000),lambda([x],primep(x) and zn_order(10,x)=x-1)));
length(sublist(makelist(i,i,2000),lambda([x],primep(x) and zn_order(10,x)=x-1)));
length(sublist(makelist(i,i,4000),lambda([x],primep(x) and zn_order(10,x)=x-1)));
length(sublist(makelist(i,i,8000),lambda([x],primep(x) and zn_order(10,x)=x-1)));
length(sublist(makelist(i,i,16000),lambda([x],primep(x) and zn_order(10,x)=x-1)));
length(sublist(makelist(i,i,32000),lambda([x],primep(x) and zn_order(10,x)=x-1)));
length(sublist(makelist(i,i,64000),lambda([x],primep(x) and zn_order(10,x)=x-1)));
</syntaxhighlight>
{{out}}
<pre>
[7,17,19,23,29,47,59,61,97,109,113,131,149,167,179,181,193,223,229,233,257,263,269,313,337,367,379,383,389,419,433,461,487,491,499]
 
35
60
116
218
390
716
1300
2430
</pre>
 
=={{header|NewLISP}}==
<syntaxhighlight lang="newlisp">
<lang NewLISP>
;;; Using the fact that 10 has to be a primitive root mod p
;;; for p to be a reptend/long prime.
Line 1,242 ⟶ 1,883:
(println (find-reptends 500))
(println (map (fn(n) (println n " --> " (length (find-reptends n)))) '(500 1000 2000 4000 8000 16000 32000 64000)))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,255 ⟶ 1,896:
64000 --> 2430
</pre>
 
=={{header|Nim}}==
{{trans|Kotlin}}
<syntaxhighlight lang="nim">import strformat
 
 
func sieve(limit: int): seq[int] =
 
var composite = newSeq[bool](limit + 1)
var p = 3
var p2 = p * p
while p2 < limit:
if not composite[p]:
for n in countup(p2, limit, 2 * p):
composite[n] = true
inc p, 2
p2 = p * p
 
for n in countup(3, limit, 2):
if not composite[n]:
result.add n
 
 
func period(n: int): int =
## Find the period of the reciprocal of "n".
var r = 1
for i in 1..(n + 1):
r = 10 * r mod n
let r1 = r
while true:
r = 10 * r mod n
inc result
if r == r1: break
 
 
let primes = sieve(64000)
var longPrimes: seq[int]
for prime in primes:
if prime.period() == prime - 1:
longPrimes.add prime
 
const Numbers = [500, 1000, 2000, 4000, 8000, 16000, 32000, 64000]
var index, count = 0
var totals = newSeq[int](Numbers.len)
for longPrime in longPrimes:
if longPrime > Numbers[index]:
totals[index] = count
inc index
inc count
totals[^1] = count
 
echo &"The long primes up to {Numbers[0]} are:"
for i in 0..<totals[0]:
stdout.write ' ', longPrimes[i]
stdout.write '\n'
 
echo "\nThe number of long primes up to:"
for i, total in totals:
echo &" {Numbers[i]:>5} is {total}"</syntaxhighlight>
 
{{out}}
<pre>The long primes up to 500 are:
7 17 19 23 29 47 59 61 97 109 113 131 149 167 179 181 193 223 229 233 257 263 269 313 337 367 379 383 389 419 433 461 487 491 499
 
The number of long primes up to:
500 is 35
1000 is 60
2000 is 116
4000 is 218
8000 is 390
16000 is 716
32000 is 1300
64000 is 2430</pre>
 
=={{header|Pascal}}==
Line 1,260 ⟶ 1,974:
www . arndt-bruenner.de/mathe/scripts/periodenlaenge.htm
 
<langsyntaxhighlight lang="pascal">
PROGRAMprogram Periode;
 
{$IFDEF FPC}
{$MODE Delphi}
{$OPTIMIZATION ON}
{$OPTIMIZATION Regvar}
Line 1,273 ⟶ 1,986:
{$else}
{$Apptype Console}
{$ENDIF}
 
uses
sysutils;
 
const
cBASIS = 10;
PRIMFELDOBERGRENZE = 6542;
{Das sind alle Primzahlen bis 2^16}
{Das reicht fuer al8le Primzahlen bis 2^32}
TESTZAHL = 500; //429496709;//High(DwordCardinal) DIV cBasis;
 
type
tPrimFeld = array [1..PRIMFELDOBERGRENZE] of Word;
 
tFaktorPotenz = record
tFaktorPotenz = record
Faktor,
Faktor, Potenz : DWordCardinal;
end;
//2*3*5*7*11*13*17*19*23 *29 > DWordCardinal also maximal 9 Faktoren
 
tFaktorFeld = array [1..9] of TFaktorPotenz;//DWord
tFaktorFeld = array[1..9] of TFaktorPotenz; //Cardinal
// tFaktorFeld = array [1..15] of TFaktorPotenz;//QWord
tFaktorisieren = class(TObject)
private
fFakZahl : DWord;
fFakBasis : DWord;
fFakAnzahl : Dword;
fAnzahlMoeglicherTeiler : Dword;
fEulerPhi : DWORD;
fStartPeriode : DWORD;
fPeriodenLaenge : DWORD;
fTeiler : array of DWord;
fFaktoren : tFaktorFeld;
fBasFakt : tFaktorFeld;
fPrimfeld : tPrimFeld;
 
tFaktorisieren = class(TObject)
procedure PrimFeldAufbauen;
private
procedure Fakteinfuegen(var Zahl:Dword;inFak:Dword);
fFakZahl: Cardinal;
function BasisPeriodeExtrahieren(var inZahl:Dword):DWord;
fFakBasis: Cardinal;
procedure NachkommaPeriode(var OutText: String);
fFakAnzahl: Cardinal;
public
fAnzahlMoeglicherTeiler: Cardinal;
constructor create; overload;
fEulerPhi: Cardinal;
function Prim(inZahl:Dword):Boolean;
fStartPeriode: Cardinal;
procedure AusgabeFaktorfeld(n : DWord);
fPeriodenLaenge: Cardinal;
procedure Faktorisierung (inZahl: DWord);
fTeiler: array of Cardinal;
procedure TeilerErmitteln;
fFaktoren: tFaktorFeld;
procedure PeriodeErmitteln(inZahl:Dword);
fBasFakt: tFaktorFeld;
function BasExpMod( b, e, m : Dword) : DWord;
fPrimfeld: tPrimFeld;
procedure PrimFeldAufbauen;
property
procedure Fakteinfuegen(var Zahl: Cardinal; inFak: Cardinal);
EulerPhi : Dword read fEulerPhi;
function BasisPeriodeExtrahieren(var inZahl: Cardinal): Cardinal;
property
procedure NachkommaPeriode(var OutText: string);
PeriodenLaenge: DWord read fPeriodenLaenge ;
public
property
constructor create; overload;
StartPeriode: DWord read fStartPeriode ;
function Prim(inZahl: Cardinal): Boolean;
end;
procedure AusgabeFaktorfeld(n: Cardinal);
procedure Faktorisierung(inZahl: Cardinal);
procedure TeilerErmitteln;
procedure PeriodeErmitteln(inZahl: Cardinal);
function BasExpMod(b, e, m: Cardinal): Cardinal;
property EulerPhi: Cardinal read fEulerPhi;
property PeriodenLaenge: Cardinal read fPeriodenLaenge;
property StartPeriode: Cardinal read fStartPeriode;
end;
 
constructor tFaktorisieren.create;
begin
inherited;
PrimFeldAufbauen;
 
fFakZahl := 0;
fFakBasis := cBASIS;
Faktorisierung(fFakBasis);
fBasFakt := fFaktoren;
 
fFakZahl := 0;
fEulerPhi := 1;
fPeriodenLaenge := 0;
fFakZahl := 0;
fFakAnzahl := 0;
fAnzahlMoeglicherTeiler := 0;
end;
 
function tFaktorisieren.Prim(inZahl:Dword Cardinal): Boolean;
{Testet auf PrimZahl}
var
Wurzel, pos: Cardinal;
begin
pos : Dword;
Begin
if fFakZahl = inZahl then
begin
result := (fAnzahlMoeglicherTeiler = 2);
exit;
end;
result := false;
if inZahl > 1 then
begin
result := true;
pos := 1;
Wurzel := trunc(sqrt(inZahl));
while fPrimFeld[pos] <= Wurzel do
begin
if (inZahl mod fPrimFeld[pos]) = 0 then
result := true;
Pos := 1;
Wurzel:= trunc(sqrt(inZahl));
While fPrimFeld[Pos] <= Wurzel do
begin
if (inZahl mod fPrimFeld[Pos])=0 then
begin
result := false;
break;
end;
inc(Pos);
IF Pos > High(fPrimFeld) then
break;
end;
end; inc(pos);
if pos > High(fPrimFeld) then
break;
end;
end;
end;
 
Procedureprocedure tFaktorisieren.PrimFeldAufbauen;
{Baut die Liste der Primzahlen bis Obergrenze auf}
const
MAX = 65536;
var
TestaufPrim, Zaehler, delta: Cardinal;
Zaehler,delta : Dword;
begin
Zaehler := 1;
fPrimFeld[Zaehler] := 2;
inc(Zaehler);
fPrimFeld[Zaehler] := 3;
 
delta := 2;
TestAufPrim TestaufPrim := 5;
repeat
if prim(TestAufPrimTestaufPrim) then
begin
inc(Zaehler);
fPrimFeld[Zaehler] := TestAufPrimTestaufPrim;
end;
inc(TestAufPrimTestaufPrim, delta);
delta := 6 - delta; // 2,4,2,4,2,4,2,
until (TestAufPrimTestaufPrim >= MAX);
 
end; {PrimfeldAufbauen}
 
procedure tFaktorisieren.Fakteinfuegen(var Zahl: Cardinal; inFak: Cardinal);
 
procedure tFaktorisieren.Fakteinfuegen(var Zahl:Dword;inFak:Dword);
var
i : DWordCardinal;
begin
inc(fFakAnzahl);
with fFaktoren[fFakAnzahl] do
begin
fEulerPhi := fEulerPhi * (inFak - 1);
Faktor := inFak;
Potenz := 0;
while (Zahl mod inFak) = 0 do
begin
Zahl := Zahl div inFak;
inc(Potenz);
end;
For i := 2 to Potenz do
fEulerPhi := fEulerPhi*inFak;
end;
for i := 2 to Potenz do
fAnzahlMoeglicherTeiler:=fAnzahlMoeglicherTeiler*(1+fFaktoren[fFakAnzahl].Potenz);
fEulerPhi := fEulerPhi * inFak;
end;
fAnzahlMoeglicherTeiler := fAnzahlMoeglicherTeiler * (1 + fFaktoren[fFakAnzahl].Potenz);
end;
 
procedure tFaktorisieren.Faktorisierung (inZahl: DWordCardinal);
var
j, og: longint;
og : longint;
begin
if fFakZahl = inZahl then
exit;
fPeriodenLaenge := 0;
fFakZahl := inZahl;
fEulerPhi := 1;
fFakAnzahl := 0;
fAnzahlMoeglicherTeiler :=1;
setlength(fTeiler,0);
 
fPeriodenLaenge := 0;
If inZahl < 2 then
fFakZahl := inZahl;
exit;
fEulerPhi := 1;
og := round(sqrt(inZahl)+1.0);
fFakAnzahl := 0;
fAnzahlMoeglicherTeiler := 1;
setlength(fTeiler, 0);
 
if inZahl < 2 then
exit;
og := round(sqrt(inZahl) + 1.0);
{Suche Teiler von inZahl}
for j := 1 to High(fPrimfeld) do
begin
If if fPrimfeld[j] > OGog then
Break;
if (inZahl mod fPrimfeld[j]) = 0 then
Fakteinfuegen(inZahl, fPrimfeld[j]);
end;
If if inZahl > 1 then
Fakteinfuegen(inZahl, inZahl);
TeilerErmitteln;
end; {Faktorisierung}
 
procedure tFaktorisieren.AusgabeFaktorfeld(n : DWordCardinal);
var
i : integer;
begin
if fFakZahl <> n then
Faktorisierung(n);
write(fAnzahlMoeglicherTeiler: 5, ' Faktoren ');
 
Forfor i := 1 to fFakAnzahl - 1 do
with fFaktoren[i] do
IFif potenz > 1 then
write(Faktor, '^', Potenz, '*')
else
write(Faktor, '*');
with fFaktoren[fFakAnzahl] do
IFif potenz > 1 then
write(Faktor, '^', Potenz)
else
write(Faktor);
 
writeln(' Euler Phi: ', fEulerPhi: 12, PeriodenLaenge: 12);
end;
 
procedure tFaktorisieren.TeilerErmitteln;
var
Position : DWordCardinal;
i,j j: DWordCardinal;
 
procedure FaktorAufbauen(Faktor: DWord;n: DWord);
procedure FaktorAufbauen(Faktor: Cardinal; n: Cardinal);
var
i, Pot: Cardinal;
Pot : DWord;
begin
Pot := 1;
i := 0;
repeat
IFif n > Low(fFaktoren) then
FaktorAufbauen(Pot * Faktor, n - 1)
else
begin
FTeiler[Position] := Pot * Faktor;
inc(Position);
end;
Pot := Pot * fFaktoren[n].Faktor;
inc(i);
until i > fFaktoren[n].Potenz;
end;
 
begin
Position := 0;
setlength(FTeiler, fAnzahlMoeglicherTeiler);
FaktorAufbauen(1, fFakAnzahl);
//Sortieren
Forfor i := Low(fTeiler) to fAnzahlMoeglicherTeiler - 2 do
begin
j := i;
while (j >= Low(fTeiler)) ANDand (fTeiler[j] > fTeiler[j + 1]) do
begin
Position := fTeiler[j];
fTeiler[j] := fTeiler[j + 1];
fTeiler[j + 1] := Position;
dec(j);
end;
end;
end;
end;
 
function tFaktorisieren.BasisPeriodeExtrahieren(var inZahl:Dword Cardinal):DWord Cardinal;
var
i, cnt, Teiler: Cardinal;
Teiler: Dword;
begin
cnt := 0;
result := 0;
Forfor i := Low(fBasFakt) to High(fBasFakt) do
begin
with fBasFakt[i] do
begin
if Faktor = 0 then
with fBasFakt[i] do
begin
IF Faktor = 0 then
BREAK;
Teiler := Faktor;
Forfor cnt := 2 to Potenz do
Teiler := Teiler * Faktor;
end;
cnt := 0;
while (inZahl <> 0) ANDand (inZahl mod Teiler = 0) do
begin
inZahl := inZahl div Teiler;
inc(cnt);
end;
IF cnt > result then
result := cnt;
end;
if cnt > result then
result := cnt;
end;
end;
 
procedure tFaktorisieren.PeriodeErmitteln(inZahl:Dword Cardinal);
var
i, TempZahl, TempPhi, TempPer, TempBasPer: Cardinal;
i,
TempZahl,
TempPhi,
TempPer,
TempBasPer: DWord;
begin
Faktorisierung(inZahl);
Line 1,564 ⟶ 2,265:
TempBasPer := BasisPeriodeExtrahieren(TempZahl);
TempPer := 0;
IFif TempZahl > 1 then
begin
Faktorisierung(TempZahl);
TempPhi := fEulerPhi;
IFif (TempPhi > 1) then
begin
Faktorisierung(TempPhi);
i := 0;
repeat
TempPer := fTeiler[i];
IFif BasExpMod(fFakBasis, TempPer, TempZahl) = 1 then
Break;
inc(i);
until i >= Length(fTeiler);
IFif i >= Length(fTeiler) then
TempPer := inZahl - 1;
end;
end;
end;
 
Faktorisierung(inZahl);
fPeriodenlaenge := TempPer;
fStartPeriode := TempBasPer;
end;
 
procedure tFaktorisieren.NachkommaPeriode(var OutText: Stringstring);
var
i, limit: integer;
i,
Rest, Rest1, Divi, basis: Cardinal;
limit : integer;
pText: pChar;
 
Rest,
Rest1,
Divi,
basis: DWord;
pText : pChar;
procedure Ziffernfolge(Ende: longint);
var
j : longint;
begin
j := i - Ende;
 
while j < 0 do
begin
Rest := Rest *Basis basis;
Rest1 := Rest Divdiv Divi;
Rest := Rest - Rest1 * Divi; //== Rest1 Mod Divi
 
pText^ := chr(Rest1 + Ord('0'));
inc(pText);
 
inc(j);
end;
 
i := Ende;
end;
 
begin
limit := fStartPeriode + fPeriodenlaenge;
 
setlength(OutText, limit + 2 + 2 + 5);
OutText[1] := '0';
OutText[2] := '.';
pText := @OutText[3];
 
Rest := 1;
Divi := fFakZahl;
Basisbasis := fFakBasis;
 
i := 0;
Ziffernfolge(fStartPeriode);
if fPeriodenlaenge = 0 then
begin
setlength(OutText, fStartPeriode + 2);
EXIT;
end;
 
pText^ := '_'; inc(pText);
inc(pText);
Ziffernfolge(limit);
pText^ := '_'; inc(pText);
inc(pText);
 
Ziffernfolge(limit + 5);
end;
 
type
tZahl = integer;
tRestFeld = array[0..31] of integer;
 
tRestFeld = array[0..31] of integer;
VAR
 
F : tFaktorisieren;
var
F: tFaktorisieren;
function tFaktorisieren.BasExpMod( b, e, m : Dword) : DWord;
 
begin
function tFaktorisieren.BasExpMod(b, e, m: Cardinal): Cardinal;
Result := 1;
begin
IF m = 0 then
Result := 1;
if m = 0 then
exit;
Result := 1;
while ( e > 0 ) do
begin
if (e ANDand 1) <> 0 then
Result := (Result * int64(b)) mod m;
b := (int64(b) * b ) mod m;
e := e shr 1;
end;
end;
 
procedure start;
var
VAR
Limit, Testzahl: Cardinal;
Testzahl longPrimCount: DWordint64;
t1, t0: TDateTime;
longPrimCount : int64;
begin
t1,t0: TDateTime;
BEGIN
 
Limit := 500;
Line 1,683 ⟶ 2,381:
 
repeat
write(Limit: 8, ': ');
repeat
if F.Prim(Testzahl) then
begin
F.PeriodeErmitteln(Testzahl);
if F.PeriodenLaenge = Testzahl - 1 then
Beginbegin
inc(longPrimCount);
IFif Limit = 500 then
write(TestZahlTestzahl, ',');
end
end;
inc(Testzahl);
until TestZahlTestzahl = Limit;
inc(Limit, Limit);
write(' .. count ', longPrimCount: 8, ' ');
t1 := time;
Ifif (t1 - t0) > 1 / 864000 then
write(FormatDateTime('HH:NN:SS.ZZZ', t1 -T0 t0));
writeln;
until Limit > 10 * 1000 * 1000;
t1 := time;
writeln;
writeln('count of long primes ',longPrimCount);
writeln('Benoetigte Zeit ',FormatDateTime('HH:NN:SS.ZZZ',T1-T0));
END;
 
t1 := time;
BEGIN
writeln;
writeln('count of long primes ', longPrimCount);
writeln('Benoetigte Zeit ', FormatDateTime('HH:NN:SS.ZZZ', t1 - t0));
 
end;
 
begin
F := tFaktorisieren.create;
writeln('Start');
start;
writeln('Fertig.');
F.free;
readln;
end.</langsyntaxhighlight>
{{out}}
<pre>sh-4.4# ./Periode
Line 1,747 ⟶ 2,445:
{{trans|Sidef}}
{{libheader|ntheory}}
<langsyntaxhighlight lang="perl">use ntheory qw/divisors powmod is_prime/;
 
sub is_long_prime {
Line 1,763 ⟶ 2,461:
for my $n (500, 1000, 2000, 4000, 8000, 16000, 32000, 64000) {
printf "Number of long primes ≤ $n: %d\n", scalar grep { is_long_prime($_) } 1 .. $n;
}</langsyntaxhighlight>
{{out}}
<pre>Long primes ≤ 500:
Line 1,780 ⟶ 2,478:
 
Faster due to going directly over primes and using znorder. Takes one second to count to 8,192,000.
<langsyntaxhighlight lang="perl">use ntheory qw/forprimes znorder/;
my($t,$z)=(0,0);
forprimes {
Line 1,786 ⟶ 2,484:
$t++ if defined $z && $z+1 == $_;
} 8192000;
print "$t\n";</langsyntaxhighlight>
{{out}}
<pre>206594</pre>
Line 1,792 ⟶ 2,490:
=={{header|Phix}}==
Slow version:
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>function is_long_prime(integer n)
<span style="color: #008080;">function</span> <span style="color: #000000;">is_long_prime</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
integer r = 1, rr, period = 0
<span style="color: #004080;">integer</span> <span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">rr</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">period</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
for i=1 to n+1 do
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
r = mod(10*r,n)
<span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">10</span><span style="color: #0000FF;">*</span><span style="color: #000000;">r</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
rr = r
<span style="color: #000000;">rr</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">r</span>
while true do
<span style="color: #008080;">while</span> <span style="color: #004600;">true</span> <span style="color: #008080;">do</span>
r = mod(10*r,n)
<span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">10</span><span style="color: #0000FF;">*</span><span style="color: #000000;">r</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
period += 1
<span style="color: #000000;">period</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
if period>=n then return false end if
<span style="color: #008080;">if</span> <span style="color: #000000;">period</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">n</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #004600;">false</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
if r=rr then exit end if
<span style="color: #008080;">if</span> <span style="color: #000000;">r</span><span style="color: #0000FF;">=</span><span style="color: #000000;">rr</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end while
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
return period=n-1
<span style="color: #008080;">return</span> <span style="color: #000000;">period</span><span style="color: #0000FF;">=</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span>
end function</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<!--</syntaxhighlight>-->
(use the same main() as below but limit maxN to 8 iterations)
 
Much faster version:
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>function is_long_prime(integer n)
<span style="color: #008080;">function</span> <span style="color: #000000;">is_long_prime</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
sequence f = factors(n-1,1)
<span style="color: #004080;">sequence</span> <span style="color: #000000;">f</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">factors</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
integer count = 0
<span style="color: #004080;">integer</span> <span style="color: #000000;">count</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
for i=1 to length(f) do
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">f</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
integer fi = f[i], e=1, base=10
<span style="color: #004080;">integer</span> <span style="color: #000000;">fi</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">f</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span> <span style="color: #000000;">e</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">base</span><span style="color: #0000FF;">=</span><span style="color: #000000;">10</span>
while fi!=0 do
<span style="color: #008080;">while</span> <span style="color: #000000;">fi</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">do</span>
if mod(fi,2)=1 then
<span style="color: #008080;">if</span> <span style="color: #7060A8;">mod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fi</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
e = mod(e*base,n)
<span style="color: #000000;">e</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">e</span><span style="color: #0000FF;">*</span><span style="color: #000000;">base</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
base = mod(base*base,n)
<span style="color: #000000;">base</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">base</span><span style="color: #0000FF;">*</span><span style="color: #000000;">base</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
fi = floor(fi/2)
<span style="color: #000000;">fi</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fi</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span>
end while
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
if e=1 then
<span style="color: #008080;">if</span> <span style="color: #000000;">e</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
count += 1
<span style="color: #000000;">count</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
if count>1 then exit end if
<span style="color: #008080;">if</span> <span style="color: #000000;">count</span><span style="color: #0000FF;">></span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
return count=1
<span style="color: #008080;">return</span> <span style="color: #000000;">count</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
 
procedure main()
<span style="color: #008080;">procedure</span> <span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
atom t0 = time()
<span style="color: #004080;">atom</span> <span style="color: #000000;">t0</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">()</span>
integer maxN = 500*power(2,14)
<span style="color: #004080;">integer</span> <span style="color: #000000;">maxN</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">500</span><span style="color: #0000FF;">*</span><span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">14</span><span style="color: #0000FF;">)</span>
--integer maxN = 500*power(2,7) -- (slow version)
<span style="color: #000080;font-style:italic;">--integer maxN = 500*power(2,7) -- (slow version)</span>
sequence long_primes = {}
<span style="color: #004080;">sequence</span> <span style="color: #000000;">long_primes</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
integer count = 0,
<span style="color: #004080;">integer</span> <span style="color: #000000;">count</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span>
n = 500,
<span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">500</span><span style="color: #0000FF;">,</span>
i = 2
<span style="color: #000000;">i</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">2</span>
while true do
<span style="color: #008080;">while</span> <span style="color: #004600;">true</span> <span style="color: #008080;">do</span>
integer prime = get_prime(i)
<span style="color: #004080;">integer</span> <span style="color: #000000;">prime</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">get_prime</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
if is_long_prime(prime) then
<span style="color: #008080;">if</span> <span style="color: #000000;">is_long_prime</span><span style="color: #0000FF;">(</span><span style="color: #000000;">prime</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
if prime<500 then
<span style="color: #008080;">if</span> <span style="color: #000000;">prime</span><span style="color: #0000FF;"><</span><span style="color: #000000;">500</span> <span style="color: #008080;">then</span>
long_primes &= prime
<span style="color: #000000;">long_primes</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">prime</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
if prime>n then
<span style="color: #008080;">if</span> <span style="color: #000000;">prime</span><span style="color: #0000FF;">></span><span style="color: #000000;">n</span> <span style="color: #008080;">then</span>
if n=500 then
<span style="color: #008080;">if</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">500</span> <span style="color: #008080;">then</span>
printf(1,"The long primes up to 500 are:\n %v\n",{long_primes})
<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 long primes up to 500 are:\n %V\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">long_primes</span><span style="color: #0000FF;">})</span>
printf(1,"\nThe number of long primes up to:\n")
<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;">"\nThe number of long primes up to:\n"</span><span style="color: #0000FF;">)</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
printf(1," %7d is %d (%s)\n", {n, count, elapsed(time()-t0)})
<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;">" %7d is %d (%s)\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">count</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>
if n=maxN then exit end if
<span style="color: #008080;">if</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">maxN</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
n *= 2
<span style="color: #000000;">n</span> <span style="color: #0000FF;">*=</span> <span style="color: #000000;">2</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
count += 1
<span style="color: #000000;">count</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
i += 1
<span style="color: #000000;">i</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
end while
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
end procedure
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
main()</lang>
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<!--</syntaxhighlight>-->
{{out}}
slow version:
Line 1,896 ⟶ 2,598:
8192000 is 206594 (1 minute and 60s)
</pre>
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">go =>
println(findall(P, (member(P,primes(500)),long_prime(P)))),
nl,
println("Number of long primes up to limit are:"),
foreach(Limit in [500,1_000,2_000,4_000,8_000,16_000,32_000,64_000])
printf(" <= %5d: %4d\n", Limit, count_all( (member(P,primes(Limit)), long_prime(P)) ))
end,
nl.
 
long_prime(P) =>
get_rep_len(P) == (P-1).
 
%
% Get the length of the repeating cycle for 1/n
%
get_rep_len(I) = Len =>
FoundRemainders = {0 : _K in 1..I+1},
Value = 1,
Position = 1,
while (FoundRemainders[Value+1] == 0, Value != 0)
FoundRemainders[Value+1] := Position,
Value := (Value*10) mod I,
Position := Position+1
end,
Len = Position-FoundRemainders[Value+1].</syntaxhighlight>
 
{{out}}
<pre>[7,17,19,23,29,47,59,61,97,109,113,131,149,167,179,181,193,223,229,233,257,263,269,313,337,367,379,383,389,419,433,461,487,491,499]
 
Number of long primes up to limit are:
<= 500: 35
<= 1000: 60
<= 2000: 116
<= 4000: 218
<= 8000: 390
<= 16000: 716
<= 32000: 1300
<= 64000: 2430</pre>
 
=={{header|Prolog}}==
{{works with|SWI Prolog}}
<langsyntaxhighlight lang="prolog">% See https://en.wikipedia.org/wiki/Full_reptend_prime
long_prime(Prime):-
is_prime(Prime),
Line 1,974 ⟶ 2,716:
 
main:-
main(256000).</langsyntaxhighlight>
 
Module for finding prime numbers up to some limit:
<langsyntaxhighlight lang="prolog">:- module(prime_numbers, [find_prime_numbers/1, is_prime/1]).
:- dynamic is_prime/1.
 
Line 2,018 ⟶ 2,760:
cross_out(S, N, P):-
Q is S + 2 * P,
cross_out(Q, N, P).</langsyntaxhighlight>
 
{{out}}
Line 2,037 ⟶ 2,779:
% 8,564,024 inferences, 0.991 CPU in 1.040 seconds (95% CPU, 8641390 Lips)
true.
</pre>
===alternative version===
the smallest divisor d of p - 1 such that 10^d = 1 (mod p)
is the length of the period of the decimal expansion of 1/p
<syntaxhighlight lang="prolog">isPrime(A):-
A1 is ceil(sqrt(A)),
between(2, A1, N),
0 =:= A mod N,!,
false.
isPrime(_).
 
divisors(N, Dlist):-
N1 is floor(sqrt(N)),
numlist(1, N1, Ds0),
include([D]>>(N mod D =:= 0), Ds0, Ds1),
reverse(Ds1, [Dh|Dt]),
( Dh * Dh < N
-> Ds1a = [Dh|Dt]
; Ds1a = Dt
),
maplist([X,Y]>>(Y is N div X), Ds1a, Ds2),
append(Ds1, Ds2, Dlist).
 
longPrime(P):-
divisors(P - 1, Dlist),
longPrime(P, Dlist).
 
longPrime(_,[]):- false.
longPrime(P, [D|Dtail]):-
powm(10, D, P) =\= 1,!,
longPrime(P, Dtail).
longPrime(P, [D|_]):-!,
D =:= P - 1.
 
isLongPrime(N):-
isPrime(N),
longPrime(N).
 
longPrimes(N, LongPrimes):-
numlist(7, N, List),
include(isLongPrime, List, LongPrimes).
 
run([]):-!.
run([Limit|Tail]):-
statistics(runtime,[Start|_]),
longPrimes(Limit, LongPrimes),
length(LongPrimes, Num),
statistics(runtime,[Stop|_]),
Runtime is Stop - Start,
writef('there are%5r long primes up to%6r [time (ms)%5r]\n',[Num, Limit, Runtime]),
run(Tail).
 
do:- longPrimes(500, LongPrimes),
writeln('long primes up to 500:'),
writeln(LongPrimes),
numlist(0, 7, List),
maplist([X, Y]>>(Y is 500 * 2**X), List, LimitList),
run(LimitList).</syntaxhighlight>
{{out}}
<pre>long primes up to 500:
[7,17,19,23,29,47,59,61,97,109,113,131,149,167,179,181,193,223,229,233,257,263,269,313,337,367,379,383,389,419,433,461,487,491,499]
there are 35 long primes up to 500 [time (ms) 7]
there are 60 long primes up to 1000 [time (ms) 16]
there are 116 long primes up to 2000 [time (ms) 42]
there are 218 long primes up to 4000 [time (ms) 98]
there are 390 long primes up to 8000 [time (ms) 242]
there are 716 long primes up to 16000 [time (ms) 603]
there are 1300 long primes up to 32000 [time (ms) 1507]
there are 2430 long primes up to 64000 [time (ms) 3851]
</pre>
 
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">#MAX=64000
If OpenConsole()=0 : End 1 : EndIf
 
Dim p.b(#MAX) : FillMemory(@p(),#MAX,#True,#PB_Byte)
For n=2 To Int(Sqr(#MAX))+1 : If p(n) : m=n*n : While m<=#MAX : p(m)=#False : m+n : Wend : EndIf : Next
 
Procedure.i periodic(v.i)
r=1 : Repeat : r=(r*10)%v : c+1 : If r<=1 : ProcedureReturn c : EndIf : ForEver
EndProcedure
 
n=500
PrintN(LSet("_",15,"_")+"Long primes upto "+Str(n)+LSet("_",15,"_"))
For i=3 To 500 Step 2
If p(i) And (i-1)=periodic(i)
Print(RSet(Str(i),5)) : c+1 : If c%10=0 : PrintN("") : EndIf
EndIf
Next
 
PrintN(~"\n")
PrintN("The number of long primes up to:")
PrintN(RSet(Str(n),8)+" is "+Str(c)) : n+n
For i=501 To #MAX+1 Step 2
If p(i) And (i-1)=periodic(i) : c+1 : EndIf
If i>n : PrintN(RSet(Str(n),8)+" is "+Str(c)) : n+n : EndIf
Next
Input()</syntaxhighlight>
{{out}}
<pre>_______________Long primes upto 500_______________
7 17 19 23 29 47 59 61 97 109
113 131 149 167 179 181 193 223 229 233
257 263 269 313 337 367 379 383 389 419
433 461 487 491 499
 
The number of long primes up to:
500 is 35
1000 is 60
2000 is 116
4000 is 218
8000 is 390
16000 is 716
32000 is 1300
64000 is 2430
</pre>
 
=={{header|Python}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="python">def sieve(limit):
primes = []
c = [False] * (limit + 1) # composite = true
Line 2,089 ⟶ 2,945:
print('\nThe number of long primes up to:')
for (i, total) in enumerate(totals):
print(' %5d is %d' % (numbers[i], total))</langsyntaxhighlight>
{{out}}
<pre>
Line 2,105 ⟶ 2,961:
64000 is 2430
</pre>
 
=={{header|Quackery}}==
 
<code>eratosthenes</code> and <code>isprime</code> are defined at [[Sieve of Eratosthenes#Quackery]].
 
<code>bsearchwith</code> is defined at [[Binary search#Quackery]].
 
<syntaxhighlight lang="quackery"> [ over size 0 swap 2swap
bsearchwith < drop ] is search ( [ --> n )
 
[ 1 over 1 - times
[ 10 * over mod ]
tuck
0 temp put
[ 10 * over mod
1 temp tally
rot 2dup != while
unrot again ]
2drop drop
temp take ] is period ( n --> n )
 
[ dup isprime not iff
[ drop false ] done
dup period 1+ = ] is islongprime ( n --> b )
64000 eratosthenes
 
[]
64000 times
[ i^ islongprime if [ i^ join ] ]
behead drop
dup dup 500 search split drop echo cr cr
' [ 500 1000 2000 4000 8000 16000 32000 64000 ]
witheach
[ dup echo say " --> "
dip dup search echo cr ]
drop</syntaxhighlight>
 
{{out}}
 
<pre>[ 7 17 19 23 29 47 59 61 97 109 113 131 149 167 179 181 193 223 229 233 257 263 269 313 337 367 379 383 389 419 433 461 487 491 499 ]
 
500 --> 35
1000 --> 60
2000 --> 116
4000 --> 218
8000 --> 390
16000 --> 716
32000 --> 1300
64000 --> 2430</pre>
 
=={{header|Racket}}==
Line 2,110 ⟶ 3,017:
{{trans|Go}} (at least '''find-period''')
 
<langsyntaxhighlight lang="racket">#lang racket
(require math/number-theory)
 
Line 2,135 ⟶ 3,042:
(module+ test
(require rackunit)
(check-equal? (map find-period '(7 11 977)) '(6 2 976)))</langsyntaxhighlight>
 
{{out}}
Line 2,152 ⟶ 3,059:
{{works with|Rakudo|2018.06}}
Not very fast as the numbers get larger.
<syntaxhighlight lang="raku" perl6line>use Math::Primesieve;
my $sieve = Math::Primesieve.new;
 
Line 2,180 ⟶ 3,087:
say "\nNumber of long primes ≤ $upto: ", +@long-primes;
$from = $upto;
}</langsyntaxhighlight>
{{out}}
<pre>Long primes ≤ 500:
Line 2,209 ⟶ 3,116:
For every &nbsp; '''doubling''' &nbsp; of the limit, it takes about roughly &nbsp; '''5''' &nbsp; times longer to compute the long primes.
===uses odd numbers===
<langsyntaxhighlight lang="rexx">/*REXX pgm calculates/displays base ten long primes (AKA golden primes, proper primes,*/
/*───────────────────── maximal period primes, long period primes, full reptend primes).*/
parse arg a /*obtain optional argument from the CL.*/
Line 2,230 ⟶ 3,137:
.len: procedure; parse arg x; r=1; do x; r= 10*r // x; end /*x*/
rr=r; do p=1 until r==rr; r= 10*r // x; end /*p*/
return p</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the internal default inputs:}}
<pre>
Line 2,261 ⟶ 3,168:
===uses odd numbers, some prime tests===
This REXX version is about &nbsp; '''2''' &nbsp; times faster than the 1<sup>st</sup> REXX version &nbsp; (because it does some primality testing).
<langsyntaxhighlight lang="rexx">/*REXX pgm calculates/displays base ten long primes (AKA golden primes, proper primes,*/
/*───────────────────── maximal period primes, long period primes, full reptend primes).*/
parse arg a /*obtain optional argument from the CL.*/
Line 2,288 ⟶ 3,195:
.len: procedure; parse arg x; r=1; do x; r= 10*r // x; end /*x*/
rr=r; do p=1 until r==rr; r= 10*r // x; end /*p*/
return p</langsyntaxhighlight>
{{out|output|text=&nbsp; is identical to the 1<sup>st</sup> REXX version.}}
 
===uses primes===
This REXX version is about &nbsp; '''5''' &nbsp; times faster than the 1<sup>st</sup> REXX version &nbsp; (because it only tests primes).
<langsyntaxhighlight lang="rexx">/*REXX pgm calculates/displays base ten long primes (AKA golden primes, proper primes,*/
/*───────────────────── maximal period primes, long period primes, full reptend primes).*/
parse arg a /*obtain optional argument from the CL.*/
Line 2,330 ⟶ 3,237:
.len: procedure; parse arg x; r=1; do x; r= 10*r // x; end /*x*/
rr=r; do p=1 until r==rr; r= 10*r // x; end /*p*/
return p</langsyntaxhighlight>
{{out|output|text=&nbsp; is identical to the 1<sup>st</sup> REXX version.}} <br>
 
=={{header|RPL}}==
{{works with|HP|49}}
« → n
« 0 1
'''DO''' 10 * n MOD SWAP 1 + SWAP
'''UNTIL''' DUP 1 ≤ '''END'''
DROP
» » '<span style="color:blue">PERIOD</span>' STO <span style="color:grey">@ ''( n → length of 1/n period )''</span>
« { } 7
'''WHILE''' DUP 500 < '''REPEAT'''
'''IF''' DUP <span style="color:blue">PERIOD</span> OVER 1 - == '''THEN''' SWAP OVER + SWAP '''END'''
NEXTPRIME
'''END'''
DROP
» '<span style="color:blue">TASK1</span>' STO
« { 500 1000 2000 4000 8000 16000 32000 } → t
« t NOT 7
'''WHILE''' DUP 1000 < '''REPEAT'''
'''IF''' DUP <span style="color:blue">PERIOD</span> OVER 1 - == '''THEN''' t OVER ≥ ROT ADD SWAP '''END'''
NEXTPRIME
'''END'''
DROP t SWAP
2 « "<" ROT + →TAG » DOLIST
» » '<span style="color:blue">TASK2</span>' STO
{{out}}
<pre>
2: {7 17 19 23 29 47 59 61 97 109 113 131 149 167 179 181 193 223 229 233 257 263 269 313 337 367 379 383 389 419 433 461 487 491 499}
1: {<500:35 <1000:60 <2000:116 <4000:218 <8000:390 <16000:716 <32000:1300}
</pre>
 
=={{header|Ruby}}==
Line 2,337 ⟶ 3,276:
Run as: $ ruby longprimes.rb
Finding long prime numbers using finding period location (translation of Python's module def findPeriod(n))
<langsyntaxhighlight Rubylang="ruby">require 'prime'
 
batas = 64_000 # limit number
Line 2,368 ⟶ 3,307:
end
 
puts "\n\nTime: #{Time.now - start}"</langsyntaxhighlight>
 
{{out}}
Line 2,386 ⟶ 3,325:
 
Alternatively, by using primitive way: converting value into string and make assessment for proper repetend position. Indeed produce same information, but with longer time.
<langsyntaxhighlight Rubylang="ruby">require 'prime'
require 'bigdecimal'
require 'strscan'
Line 2,423 ⟶ 3,362:
end
 
puts "\n\nTime: #{Time.now - start}"</langsyntaxhighlight>
 
{{out}}
Line 2,433 ⟶ 3,372:
{{trans|Crystal of Sidef}}
Fastest version.
<langsyntaxhighlight lang="ruby">def prime?(n) # P3 Prime Generator primality test
return n | 1 == 3 if n < 5 # n: 2,3|true; 0,1,4|false
return false if n.gcd(6) != 1 # this filters out 2/3 of all integers
Line 2,465 ⟶ 3,404:
puts "Number of long primes ≤ #{n}: #{(7..n).count { |pc| long_prime? pc }}"
end
puts "\nTime: #{(Time.now - start)} secs"</langsyntaxhighlight>
 
{{out}}
Line 2,484 ⟶ 3,423:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">// main.rs
// References:
// https://en.wikipedia.org/wiki/Full_reptend_prime
Line 2,511 ⟶ 3,450:
 
fn is_long_prime(sieve: &PrimeSieve, prime: usize) -> bool {
if !sieve.is_prime(prime) {
return false;
}
if 10 % prime == 0 {
return false;
Line 2,540 ⟶ 3,482:
let mut prime = 3;
while prime < limit2 {
if sieve.is_prime(prime) && is_long_prime(&sieve, prime) {
if prime < limit1 {
print!("{} ", prime);
Line 2,557 ⟶ 3,499:
fn main() {
long_primes(500, 8192000);
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="rust">// prime_sieve.rs
use crate::bit_array;
 
Line 2,594 ⟶ 3,536:
!self.composite.get(n / 2 - 1)
}
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="rust">// bit_array.rs
pub struct BitArray {
array: Vec<u32>,
Line 2,619 ⟶ 3,561:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,640 ⟶ 3,582:
Number of long primes up to 4096000: 108381
Number of long primes up to 8192000: 206594
</pre>
===Rust FP===
<syntaxhighlight lang="rust">fn is_oddprime(n: u64) -> bool {
let limit = (n as f64).sqrt().ceil() as u64;
(3..=limit).step_by(2).all(|a| n % a > 0)
}
 
fn divisors(n: u64) -> Vec<u64> {
let list1: Vec<u64> = (1..=(n as f64).sqrt().floor() as u64)
.filter(|d| n % d == 0).collect();
let list2: Vec<u64> = list1.iter().rev()
.skip_while(|&d| d * d == n).map(|d| n / d).collect();
[list1, list2].concat()
}
 
fn power_mod(base: u64, exp: u64, modulo: u64) -> u64 {
fn iter(base: u64, modu: &u64, exp: u64, res: u64) -> u64 {
if exp > 0 {
let base1 = (base * base) % modu;
let res1 = if exp & 1 > 0 {(base * res) % modu} else {res};
iter(base1, modu, exp >> 1, res1)
}
else {res}
}
iter(base, &modulo, exp, 1)
}
 
// the smallest divisor d of p-1 such that 10^d = 1 (mod p)
// is the length of the period of the decimal expansion of 1/p
fn is_longprime(p: u64) -> bool {
match divisors(p - 1).into_iter()
.skip_while(|&d| power_mod(10, d, p) != 1)
.next() {
Some(d) => d + 1 == p,
None => false
}
}
 
fn long_primes() -> impl Iterator<Item = u64> {
(7..).step_by(2).filter(|&p|is_oddprime(p))
.filter(|&p| is_longprime(p))
}
 
fn main() {
println!("long primes up to 500:");
let list500: Vec<u64> = long_primes()
.take_while(|&p| p <= 500)
.collect();
println!("{:?}\n", list500);
let limits: Vec<u64> = (0..8).map(|n| 2u64.pow(n) * 500).collect();
for limit in limits {
let start = std::time::Instant::now();
let count = long_primes().take_while(|&p| p <= limit).count();
let duration = start.elapsed().as_millis();
println!("there are {:4} long primes up to {:5} [time(ms) {:3}]",
count, limit, duration);
}
}</syntaxhighlight>
{{out}}
<pre>
long primes up to 500:
[7, 17, 19, 23, 29, 47, 59, 61, 97, 109, 113, 131, 149, 167, 179, 181, 193, 223, 229, 233, 257, 263, 269, 313, 337, 367, 379, 383, 389, 419, 433, 461, 487, 491, 499]
 
there are 35 long primes up to 500 [time(ms) 0]
there are 60 long primes up to 1000 [time(ms) 1]
there are 116 long primes up to 2000 [time(ms) 2]
there are 218 long primes up to 4000 [time(ms) 5]
there are 390 long primes up to 8000 [time(ms) 13]
there are 716 long primes up to 16000 [time(ms) 31]
there are 1300 long primes up to 32000 [time(ms) 36]
there are 2430 long primes up to 64000 [time(ms) 41]
</pre>
 
=={{header|Scala}}==
<syntaxhighlight lang="scala">object LongPrimes extends App {
def primeStream = LazyList.from(3, 2)
.filter(p => (3 to math.sqrt(p).ceil.toInt by 2).forall(p % _ > 0))
def longPeriod(p: Int): Boolean = {
val mstart = 10 % p
@annotation.tailrec
def iter(mod: Int, period: Int): Int = {
val mod1 = (10 * mod) % p
if (mod1 == mstart) period
else iter(mod1, period + 1)
}
iter(mstart, 1) == p - 1
}
 
val longPrimes = primeStream.filter(longPeriod(_))
println("long primes up to 500:")
println(longPrimes.takeWhile(_ <= 500).mkString(" "))
println
val limitList = Seq.tabulate(8)(math.pow(2, _).toInt * 500)
for (limit <- limitList) {
val count = longPrimes.takeWhile(_ <= limit).length
println(f"there are $count%4d long primes up to $limit%5d")
}
}</syntaxhighlight>
{{out}}
<pre>
long primes up to 500:
7 17 19 23 29 47 59 61 97 109 113 131 149 167 179 181 193 223 229 233 257 263 269 313 337 367 379 383 389 419 433 461 487 491 499
 
there are 35 long primes up to 500
there are 60 long primes up to 1000
there are 116 long primes up to 2000
there are 218 long primes up to 4000
there are 390 long primes up to 8000
there are 716 long primes up to 16000
there are 1300 long primes up to 32000
there are 2430 long primes up to 64000
</pre>
 
=={{header|Sidef}}==
The smallest divisor d of p-1 such that 10^d = 1 (mod p), is the length of the period of the decimal expansion of 1/p.
<langsyntaxhighlight lang="ruby">func is_long_prime(p) {
 
for d in (divisors(p-1)) {
Line 2,660 ⟶ 3,716:
for n in ([500, 1000, 2000, 4000, 8000, 16000, 32000, 64000]) {
say ("Number of long primes ≤ #{n}: ", primes(n).count_by(is_long_prime))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,677 ⟶ 3,733:
Alternatively, we can implement the ''is_long_prime(p)'' function using the `znorder(a, p)` built-in method, which is considerably faster:
 
<langsyntaxhighlight lang="ruby">func is_long_prime(p) {
znorder(10, p) == p-1
}</langsyntaxhighlight>
 
=={{header|Swift}}==
 
<langsyntaxhighlight lang="swift">public struct Eratosthenes: Sequence, IteratorProtocol {
private let n: Int
private let limit: Int
Line 2,747 ⟶ 3,803:
for key in counts.keys.sorted() {
print("There are \(counts[key]!) long primes less than \(key)")
}</langsyntaxhighlight>
 
{{out}}
Line 2,763 ⟶ 3,819:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<langsyntaxhighlight lang="vbnet">Imports System, System.Collections.Generic, System.Linq, System.Console
 
Module LongPrimes
Line 2,802 ⟶ 3,858:
End Function
 
End Module</langsyntaxhighlight>
{{out}}
Same output as C#.
Line 2,810 ⟶ 3,866:
{{libheader|Wren-fmt}}
{{libheader|Wren-math}}
<langsyntaxhighlight ecmascriptlang="wren">import "./fmt" for Fmt
import "./math" for Int
// finds the period of the reciprocal of n
Line 2,851 ⟶ 3,907:
var i = 0
for (total in totals) {
SystemFmt.print(" %(Fmt.$5d is $d(5", numbers[i])), is %(total)")
i = i + 1
}</langsyntaxhighlight>
 
{{out}}
Line 2,874 ⟶ 3,930:
{{trans|C}}
{{works with|Windows XBasic}}
<langsyntaxhighlight lang="xbasic">
PROGRAM "longprimes"
VERSION "0.0002"
Line 2,975 ⟶ 4,031:
 
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,997 ⟶ 4,053:
Using GMP (GNU Multiple Precision Arithmetic Library, probabilistic
primes), because it is easy and fast to generate primes.
<langsyntaxhighlight lang="zkl">var [const] BN=Import("zklBigNum"); // libGMP
primes,p := List.createLong(7_000), BN(3); // one big alloc vs lots of allocs
while(p.nextPrime()<=64_000){ primes.append(p.toInt()) } // 6412 of them, skipped 2
Line 3,013 ⟶ 4,069:
}
period
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="zkl">fiveHundred:=longPrimes.filter('<(500));
println("The long primes up to 500 are:\n",longPrimes.filter('<(500)).concat(","));
 
Line 3,021 ⟶ 4,077:
foreach n in (T(500, 1000, 2000, 4000, 8000, 16000, 32000, 64000)){
println(" %5d is %d".fmt( n, longPrimes.filter1n('>(n)) ));
}</langsyntaxhighlight>
{{out}}
<pre>
3,026

edits