python - Why does this script get stuck in infinite loop for some cases? -
i'm re-working old python script. while running through random test cases, i'm noticing stuck in infinite loop cases, not others. script project euler problem 3 (works question prompt, never noticed random infinite loops). work 10, 19, 51, 600851475143. gets stuck in infinite loop 152. haven't tried others, thought enough test cases notice 'odd'.
here's code:
import sys def largestprime(n): largest_prime = 0 # initialize largest prime d = 2 # set first value factor evaluation while n > 1: # n divided each factor later on while n % d == 0: # check if n divisible factor if d > largest_prime: # check if d greater largest_prime largest_prime = d # if so, set largest_prime = d n /= d # if so, can divide n d find remaining factors d += 1 return largest_prime def main(): # make list of command line arguments, omitting [0] element # script itself. args = sys.argv[1:] if not args: #if list empty; return message & exit print ("usage: euler003.py 'n'") sys.exit(1) if len(args) > 1: #if list less 1; return message & exit print ("you've entered many arguments; usage: euler001.py 'n'") sys.exit(1) largest = largestprime(int(args[0])) print (largest) # standard boilerplate calls main() function. if __name__ == "__main__": main()
placen/=d
outside if
(but inside while
) in def largestprime(n):
because in code, n/=d
when d
greater largest_prime
wrong. n/=d
must done till n % d == 0
while n % d == 0: if d > largest_prime: largest_prime = d n /= d d += 1