@qtip2001/

Advanced Prime Detection

Python

Requires a very high IQ (200+)

fork
loading
Files
  • main.py
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# Quentin Bishop
# 29 Nov 2018
import random
from time import time

def trial(n, d, r):
  a = random.randint(2, n-1)
  val = pow(a,d,n) -1
  if val%n == 0:
    return True
  for s in range(0, r):
    val = pow(a,d*(2**s), n) + 1
    if val%n == 0:
      return True
  return False

def dr(n):
  r = 0
  n= n-1
  while (n)%2 == 0:
    n = n//2
    r += 1
  d = n
  return(d,r)

def is_prime(n):
  if n%2 == 0:
    return False
  d,r = dr(n)
  for k in range(10):
    if trial(n,d,r) == False:
      return False
  return True

def is_square(apositiveint):
  x = apositiveint // 2
  seen = set([x])
  while x * x != apositiveint:
    x = (x + (apositiveint // x)) // 2
    if x in seen: return False
    seen.add(x)
  return True

def factorize(n):
  x = int(n**0.5)
  while True:
    if is_square(x**2-n):
      return (x+int((x**2-n)**0.5), x-int((x**2-n)**0.5))
    x+=1

def run_trial(e):
  t0 = time()
  p1 = 2**(e-1)+1+random.randint(1,2**(e-6))*2
  while not is_prime(p1):
    p1+=2
  p2 = 2**(e-1)+1+random.randint(1,2**(e-6))*2
  while not is_prime(p2):
    p2+=2
  t1 = time()
  #print('Seconds to generate primes: %f' %(t1-t0))
  m = p1*p2
  t2 = time()
  print(factorize(m))
  t3 = time()
  return(t1-t0, t3-t2)
  #print(f)
  #print('Seconds to factorize: %f' %(t3-t2))

def run_multiple_trials(e):
  pt = 0
  ft = 0
  for x in range(10):
    trial = run_trial(e)
    pt += trial[0]
    ft += trial[1]
  print(pt/10, ft/10)

run_multiple_trials(32)