Why does this script get stuck in infinite loop for some cases?

时间:2015-04-23 05:37:11

标签: python while-loop infinite-loop

I'm re-working an old python script. While running it through some random test cases, I'm noticing that it will get stuck in an infinite loop for some cases, but not for others. This script is for Project Euler Problem 3 (works for question prompt, so never noticed random infinite loops). This will work for 10, 19, 51, 600851475143. It gets stuck in an infinite loop for 152. I haven't tried others, but thought this was enough test cases to notice something 'odd'.

Here's the code:

import sys

def largestPrime(n):
    largest_prime = 0 # initialize largest prime
    d = 2 # set first value for factor evaluation

    while n > 1: # n will be divided by each factor later on
        while n % d == 0: # check if n is divisible by factor
            if d > largest_prime: # check if d is greater than largest_prime
                largest_prime = d # if so, set largest_prime = d
                n /= d # if so, can divide n by d to find remaining factors
        d += 1

    return largest_prime


def main():
    # Make a list of command line arguments, omitting the [0] element
    # which is the script itself.
    args = sys.argv[1:]
    if not args: #if list is empty; return message & exit
        print ("Usage: euler003.py 'n'")
        sys.exit(1)

    if len(args) > 1: #if list less than 1; return message & exit
        print ("You've entered too many arguments; Usage: euler001.py 'n'")
        sys.exit(1)

    largest = largestPrime(int(args[0]))
    print (largest)


# This is the standard boilerplate that calls the main() function.    
if __name__ == "__main__":
    main()

1 个答案:

答案 0 :(得分:3)

Placen/=d outside the if (but inside the while) in def largestPrime(n): Because in your code, you do n/=d only when d is greater than largest_prime which is wrong. n/=d must be done till n % d == 0

while n % d == 0: 
    if d > largest_prime:
       largest_prime = d 
    n /= d 
d += 1