Reputation: 198
I have written this code (in python) for factorize a integer in prime numbers (Fermat's theorem).
#!/usr/bin/python2
import random,math
n=590632926550117049
a=math.ceil(math.sqrt(n))
b2=a*a-n
while math.sqrt(b2)!=math.floor(math.sqrt(b2)):
a=a+1
b2=a*a-n
b=math.sqrt(b2)
p=a+b
q=a-b
print("p =",p)
print("q =",q)
The number n=590632926550117049 is the product of 57848543*10209987943 but my program returns: 1156469901*510720535. Why ?
EDIT: i.e. with 187 or 15 or another number works fine.
Upvotes: 1
Views: 762
Reputation: 11424
math.sqrt() uses standard IEEE 64-bit values. It can only calculate accurately for arguments less than ~2**53. Your value for n is larger than that.
If you want exact integer square roots for large numbers, I would recommend gmpy2.
Disclaimer: I maintain gmpy2.
Edit: Here is an updated version of your program.
import gmpy2
n = 590632926550117049
a = gmpy2.isqrt(n) + 1
b2 = a * a - n
while not gmpy2.is_square(b2):
a = a + 1
b2 = a * a - n
b = gmpy2.isqrt(b2)
p = a + b
q = a - b
print("p =", p)
print("q =", q)
Upvotes: 2