Skip to content

Instantly share code, notes, and snippets.

@orisano
Last active March 15, 2017 12:19
Show Gist options
  • Save orisano/ff9b09ab0d69b5b77ea17722bd01e1fd to your computer and use it in GitHub Desktop.
Save orisano/ff9b09ab0d69b5b77ea17722bd01e1fd to your computer and use it in GitHub Desktop.
dが与えられた時にnに対して素因数分解を試みるやつ
from fractions import gcd
import random
from typing import Optional, Tuple
def given_d(n: int, e: int, d: int) -> Optional[Tuple[int, int]]:
ktot = e * d - 1
s = (ktot & -ktot).bit_length() - 1
t = ktot >> s
limit = 1000
for _ in range(limit):
a = random.randrange(2, n)
x = pow(a, t, n)
for i in range(s):
y = x * x % n
if x not in (1, n - 1) and y == 1:
p = gcd(x + 1, n)
assert n % p == 0
return p, n // p
x = y
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment