RSA Factoring Challenge
RSA Factoring Challenge
#!/usr/bin/python3
import time
import math
import sys
def pollard_rho(n):
# Check if the number is even
if n % 2 == 0:
return 2
x=2
y=2
d=1
# Define the function for generating the next value in the sequence
f = lambda x: (x**2 + 1) % n
return d
def is_prime(num):
# Check if a number is prime
if num < 2:
# If num is less than 2, it is not prime, so return False
return False
for i in range(2, int(math.sqrt(num)) + 1):
# If num is divisible by any number in the range [2, sqrt(num)],\
# it is not prime, so return False
if num % i == 0:
return False
# If num is not divisible by any number in the \
# range [2, sqrt(num)], it is prime, so return True
return True
def main():
# Check if the correct number of command-line arguments is provided
if len(sys.argv) != 2:
print("Usage: python factorize.py <file>")
return
file_path = sys.argv[1]
start_time = time.time()
try:
with open(file_path, 'r') as file:
# Read the first line of the file and convert it to an integer
number = int(file.readline().strip())
# Factorize the number using Pollard's rho algorithm
p = pollard_rho(number)
# Continue factorizing until a prime factor is found
while not is_prime(p):
p = pollard_rho(p)
q = number // p
# The number is prime
if p == number or q == number:
print(f"{number} is prime.")
else:
# Print the prime factors
print(f"{number}={p}*{q}")
except FileNotFoundError:
print(f"File '{file_path}' not found.")
if __name__ == '__main__':
main()
FACTORS
#!/usr/bin/python3
Import time
import math
import sys
def pollard_rho(n):
if n % 2 == 0:
return 2
x=2
y=2
d=1
# Define the function f(x) using a lambda function
f = lambda x: (x**2 + 1) % n
# Loop until a non-trivial factor is found
while d == 1:
# Generate new values for x using the function f(x)
x = f(x)
def main():
# Check if the correct number of command-line arguments is provided
if len(sys.argv) != 2:
# Print the correct usage of the program
print("Usage: python factorize.py <file>")
# Exit the program if the correct arguments are not provided
return
# Get the file path from the command-line argument
file_path = sys.argv[1]
# start timing
start_time = time.time()
try:
# Open the file in read mode
with open(file_path, 'r') as file:
# Read all lines of the file into a lis
numbers = file.readlines()
# Iterate through each number in the list
for number in numbers:
# Convert the string number to an integer
num = int(number.strip())
# Factorize the number using Pollard's rho algorithm
factor = pollard_rho(num)
# If the factor is equal to the original number
if factor == num:
# Print that the number is prime
print(f"{num} is prime.")
else:
# Print the factors of the number
print(f"{num}={factor}*{num // factor}")
if __name__ == '__main__':
main() # Call the main function when the script is executed