RosettaCodeData/Task/Pierpont-primes/Python/pierpont-primes.py

72 lines
1.7 KiB
Python
Raw Permalink Normal View History

2026-02-01 16:33:20 -08:00
from random import randrange
2023-07-01 11:58:00 -04:00
# Copied from https://rosettacode.org/wiki/Miller-Rabin_primality_test#Python
2026-02-01 16:33:20 -08:00
def is_Prime(n: int):
2023-07-01 11:58:00 -04:00
"""
Miller-Rabin primality test.
A return value of False means n is certainly not prime. A return value of
True means n is very likely a prime.
"""
2026-02-01 16:33:20 -08:00
#Miller-Rabin test for primes
if n in [2,3,5,7]:
return True
elif n<10:
2023-07-01 11:58:00 -04:00
return False
s = 0
d = n-1
while d%2==0:
d>>=1
s+=1
assert(2**s * d == n-1)
def trial_composite(a):
if pow(a, d, n) == 1:
return False
for i in range(s):
if pow(a, 2**i * d, n) == n-1:
return False
return True
for i in range(8):#number of trials
2026-02-01 16:33:20 -08:00
a = randrange(2, n)
2023-07-01 11:58:00 -04:00
if trial_composite(a):
return False
return True
def pierpont(ulim, vlim, first):
p = 0
p2 = 1
p3 = 1
pp = []
2025-08-11 18:05:26 -07:00
for v in range(vlim):
for u in range(ulim):
2023-07-01 11:58:00 -04:00
p = p2 * p3
if first:
p = p + 1
else:
p = p - 1
if is_Prime(p):
pp.append(p)
p2 = p2 * 2
p3 = p3 * 3
p2 = 1
pp.sort()
return pp
def main():
2025-08-11 18:05:26 -07:00
print("First 50 Pierpont primes of the first kind:")
2023-07-01 11:58:00 -04:00
pp = pierpont(120, 80, True)
2025-08-11 18:05:26 -07:00
for i in range(50):
2026-02-01 16:33:20 -08:00
print("%8d " % pp[i], "\n"*((i - 9) % 10 == 0), end="")
2025-08-11 18:05:26 -07:00
print("First 50 Pierpont primes of the second kind:")
2023-07-01 11:58:00 -04:00
pp2 = pierpont(120, 80, False)
2025-08-11 18:05:26 -07:00
for i in range(50):
2026-02-01 16:33:20 -08:00
print("%8d " % pp2[i], "\n"*((i - 9) % 10 == 0), end="")
2025-08-11 18:05:26 -07:00
print("250th Pierpont prime of the first kind:", pp[249])
print("250th Pierpont prime of the second kind:", pp2[249])
2023-07-01 11:58:00 -04:00
main()