princeofsudan

ProjectEuler#3 Largest prime factor

Mar 2nd, 2013
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.10 KB | None | 0 0
  1. #The prime factors of 13195 are 5, 7, 13 and 29.
  2.  
  3. #What is the largest prime factor of the number 600851475143 ?
  4.  
  5. #Algorithm from http://jonlandrum.com/2012/09/10/calculating-the-largest-prime-factor-of-a-number/
  6. #1. Set the factor variable to 2 (the first prime)
  7. #2. Determine if the user input is divisible by factor
  8. #A. If so, repeatedly divide the user input by factor until it is not evenly divisible anymore. If the user input is #not divisible by factor, skip this step.
  9. #B. Iterate factor to the next prime, and start step 2 again.
  10. #3. Continue like so until the user input is equal to the final value of factor, which is then your answer.
  11.  
  12. def isPrime(n):
  13.     '''check if integer n is a prime'''
  14.     # range starts with 2 and only needs to go up the square-root of n
  15.     for x in range(2, int(n**0.5)+1):
  16.         if n % x == 0:
  17.             return False
  18.     return True
  19.  
  20. input = 600851475143
  21. factor = 2
  22.  
  23. while input != factor:
  24.     while input % factor == 0:
  25.         input = input / factor
  26.    
  27.     factor += 1
  28.     while not isPrime(factor):
  29.         factor += 1
  30.        
  31.    
  32. print input
Advertisement
Add Comment
Please, Sign In to add comment