1

The code:

total = 0

for number in xrange(10000):
    divisors = 0
    divisors2 = 0

    for dividend in xrange(1, number/2):
        if number % dividend == 0:
            divisors = divisors + dividend

    for dividend2 in xrange(1, divisors/2):
        if divisors % dividend2 == 0:
            divisors2 = divisors2 + dividend2

    if number == divisors2:
        total = total + number + divisors

print total 

The code is supposed to generate amicable numbers(i.e. number that total number of divisors less than itself equal another number that's total number of divisors equal the original number, see Project Euler, problem 21) under 10,000 and add them as it finds them. It's generating 48, which is way too low.

The program ran a lot faster than I expected it to: I'm running through a lot of numbers and I know for a fact that this isn't a very fast way to get the proper divisors, so I suspected something was up with the loop, either that Python was just stopping unexpectedly, or was running the loops out of order. If I put a command to print divisors before the beginning of the next loop, it goes on forever, and tends to print long lines of the same number. Something strange is definitely going on here. I googled "strange loop behavior", and searched here, to no avail. I also checked [here].2

What's going on and what should I do about it?

Thank you in advance.

4

3 回答 3

3

这里有几个问题:

它应该是

total = total + number

而且,range(1,x) 只运行到 x-1。因此,您需要指定 range(1, n/2 + 1)

于 2012-10-26T22:17:11.763 回答
2
xrange(1, n)

给你从1 ... n-1. 要从中获取数字1 ... n,您需要这样做xrange(1, n+1)。您在代码中犯了两次这个错误。

您也没有检查a != b原始问题中的情况。

于 2012-10-26T21:59:23.317 回答
1

Your algorithm's broken. Let's take the amicable number given in the example, 284, and run it through your code:

number = 284
divisors = divisors2 = 0

for dividend in range(1, number/2): #goes through all the numbers (1, 2, ..., 141)
    if not number % dividend: divisors += dividend 

#divisors = 78

for dividend2 in range(1, divisors/2): #goes through all the numbers (1, 2, ..., 38)
    if not divisors % dividend2: divisors2 += dividend2

#divisors2 = 51

if number == divisors2:
    #number != divisors2, because 284 != 51
    #the amicable number never gets added to your sum
于 2012-10-26T22:35:00.817 回答