import math
import random
# Pollard Rho algorithm
def pollard_rho(n, c=2, maxtries=50000):
if n <= 1:
return None
if n % 2 == 0:
return 2
x = random.randint(1, n - 1)
y = x
d = 1
for _ in range(maxtries):
x = (pow(x, 2, n) + c) % n
y = (pow(y, 2, n) + c) % n
y = (pow(y, 2, n) + c) % n
d = gcd(abs(x - y), n)
if d > 1 and d != n:
return d
return None
# Euclidean algorithm for calculating the greatest common divisor (GCD)
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
# Full factorization function using Pollard Rho
def factorize(n):
factors = []
if n <= 1:
return factors
# Check small factors
for i in range(2, int(math.sqrt(n)) + 1):
while n % i == 0:
factors.append(i)
n //= i
# Use Pollard Rho for remaining factor
if n > 1:
factor = pollard_rho(n)
if factor is not None:
factors.append(factor)
else:
print("Pollard Rho failed to find a factor for", n)
return factors
# Example usage
n = 123456789
factors = factorize(n)
print(f"The factors of {n} are: {factors}")
This code first checks for small factors using simple division, then uses the Pollard Rho algorithm to find any remaining factors. Note that the Pollard Rho algorithm may not always find a factor, and in that case, it will print a message. For larger numbers, more advanced factorization methods like Quadratic Sieve or Elliptic Curve Method are more efficient.