fork(9) download
  1. # pollard p-1 factoring method
  2.  
  3. def ilog(b, n): # max e where b**e <= n
  4. lo, blo, hi, bhi = 0, 1, 1, b
  5. while bhi < n:
  6. lo, blo, hi, bhi = hi, bhi, hi+hi, bhi*bhi
  7. while 1 < (hi - lo):
  8. mid = (lo + hi) // 2
  9. bmid = blo * pow(b, (mid - lo))
  10. if n < bmid: hi, bhi = mid, bmid
  11. elif bmid < n: lo, blo = mid, bmid
  12. else: return mid
  13. if bhi == n: return hi
  14. return lo
  15.  
  16. def gcd(a,b): # euclid's algorithm
  17. if b == 0: return a
  18. return gcd(b, a%b)
  19.  
  20. def primegen(start=0): # stackoverflow.com/a/20660551
  21. if start <= 2: yield 2 # prime (!) the pump
  22. if start <= 3: yield 3 # prime (!) the pump
  23. ps = primegen() # sieving primes
  24. p = next(ps) and next(ps) # first sieving prime
  25. q = p * p; D = {} # initialization
  26. def add(m, s): # insert multiple/stride
  27. while m in D: m += s # find unused multiple
  28. D[m] = s # save multiple/stride
  29. while q <= start: # initialize multiples
  30. x = (start // p) * p # first multiple of p
  31. if x < start: x += p # must be >= start
  32. if x % 2 == 0: x += p # ... and must be odd
  33. add(x, p+p) # insert in sieve
  34. p = next(ps) # next sieving prime
  35. q = p * p # ... and its square
  36. c = max(start-2, 3) # first prime candidate
  37. if c % 2 == 0: c += 1 # must be odd
  38. while True: # generate infinite list
  39. c += 2 # next odd candidate
  40. if c in D: # c is composite
  41. s = D.pop(c) # fetch stride
  42. add(c+s, s) # add next multiple
  43. elif c < q: yield c # c is prime; yield it
  44. else: # (c == q) # add p to sieve
  45. add(c+p+p, p+p) # insert in sieve
  46. p = next(ps) # next sieving prime
  47. q = p * p # ... and its square
  48.  
  49. def pminus1(n, b, x=2):
  50. q = 0; pgen = primegen(); p = next(pgen)
  51. while p < b:
  52. x = pow(x, p**ilog(p,b), n)
  53. q, p = p, next(pgen)
  54. g = gcd(x-1, n)
  55. if 1 < g < n: return g
  56. return False
  57.  
  58. print pminus1(10001, 10)
  59.  
  60. print pminus1(834126253476422235279396896780306823377996256349,125000)# your code goes here
Success #stdin #stdout 0.5s 9016KB
stdin
Standard input is empty
stdout
73
121645431297608956949367975807331201