interplane.Get Omega
Read in your language

omega-rosetta

aien-dev/omega-rosetta

Brought by drakestapleton

branch main Branches Tags History

omega-rosetta / tasks / miller-rabin-primality-test / oracle.py

30 lines · 1151 bytes Raw Blame History
1# Independent reference for "Miller-Rabin primality test" (Python 3, standard library only).
2# expected.txt is this program's stdout; omc never produced it.
3import math
4def prime(n):
5 # trial division for small n; for large n, a strong-pseudoprime test with every prime base below 40
6 if n < 2:
7 return False
8 if n < 10**6:
9 return all(n % d for d in range(2, math.isqrt(n) + 1))
10 d, s = n - 1, 0
11 while d % 2 == 0:
12 d //= 2
13 s += 1
14 for a in [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]:
15 if n % a == 0:
16 return False
17 x = pow(a, d, n)
18 if x in (1, n - 1):
19 continue
20 for _ in range(s - 1):
21 x = x * x % n
22 if x == n - 1:
23 break
24 else:
25 return False
26 return True
27print("primes below 100: " + " ".join(str(n) for n in range(100) if prime(n)))
28for n in [561, 1105, 1729, 2047, 3215031751, 2147483647, 3825123056546413051, 4611686018427387903,
29 2305843009213693951, 9223372036854775783, 18446744073709551557, 18446744073709551615]:
30 print(f"{n}: {'prime' if prime(n) else 'composite'}")