MonroCoury

factor.py

Nov 24th, 2017
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.38 KB | None | 0 0
  1. #problem 3
  2. #Fastest approach is to use yafu rather than attempting to wrtie something yourself
  3. #Yafu uses several modern algorithms including quadratic sieve and even the infamous general number field sieve
  4. #but quadratic sieve is the most appropriate for the number we need to factor, and it's very fast.
  5. #Also yafu is written in c/c++ so it's far faster than the sieve of atkins or the sieve of eranthoses
  6.  
  7. import time, os
  8.  
  9. def yafu_factor(yafu_path, yafu_bin, num):#create a function to factor a given number using yafu
  10.     os.chdir(yafu_path)#set the working directory to where yafu binary is located
  11.     os.system(yafu_bin + " factor(%d) > tmp" % num)#use yafu_bin factor(num) to get the factors and send them to a file tmp
  12.     with open("tmp", "r") as yafu_res:#read the contents of the file
  13.         res = yafu_res.read()
  14.  
  15.     factors = [ln for ln in res.split("\n") if "P" in ln]#get the prime factors and discard everything else
  16.  
  17.     for i in range(len(factors)):#clean the resulting list and convert the factors into integers (you get them as strings)
  18.         factors[i] = int(factors[i].split("=")[1])
  19.  
  20.     return factors
  21.  
  22. def solve_EU_3():
  23.     return max(yafu_factor("D:\One\Factoring\Yafu", "yafu-Win32.exe", 600851475143))
  24.  
  25. start = time.clock()
  26. print("Solution is: %d. Took %d seconds." % (solve_EU_3(), time.clock() - start))
  27. #It is so fast the time module can't measure it!
Advertisement
Add Comment
Please, Sign In to add comment