I was testing the basic version of the Fermat Factorization method, so I'm not using any improvement whatsoever. The code I wrote in Python works as fast as expected for those numbers obtained by relatively close primes.
import math
N = int(input("Insert a large number: "))
def fermat_factorization(N: int) -> list[int]:
if N % 2 == 0:
return [2, N // 2]
a = math.isqrt(N) + 1
b_square = a**2 - N
while not math.sqrt(b_square).is_integer():
a += 1
b_square = a**2 - N
b = math.isqrt(b_square)
return [a+b, a-b]
factors = fermat_factorization(N)
print(f"\nThe factor of {N} are {factors}")
However, upon checking for some large Mersenne primes (e.g. 2147483647), and playing with some more from here, the output missed the marked completely (2147483647 gets factorized into 268435456*8). Is there some error in the code or should I expect the algorithm to fail for large primes?
math.sqrtuses floating-point math, which isn’t precise enough for the size of integers you’re working with. You can discover this by doing some debugging:Using integer math (with the fix @MarkTolonen suggested for the square
Nissue) will work: