frustrated stupid newbie question
Joshua Macy
l0819m0v0smfm001 at sneakemail.com
Tue Mar 12 23:39:08 EST 2002
Scott Kurland wrote:
>>>>>Why isn't this $%^*#$% program working?
>>>>>
>>>>>#Searching for perfect numbers
>>>>>
>>>>>howhigh= input ("How high should I check?")
>>>>>for number in range (1,howhigh):
>>>>> factorsum = 0
>>>>> halfnumber=number/2
>>>>> for checking in range (1,halfnumber):
>>>>> if number/checking == int (number/checking):
>>>>> factorsum = factorsum + checking
>>>>> if number == factorsum:
>>>>> print number
>>>>>
>>>>>
>>>Well, I was expecting failure, which we got. What I hoped for was the
>>>
> two
>
>>>perfect numbers between 1 and 50, 6 and 28.
As others pointed out, you're being bitten both by integer division
and range not extending as high as you thought. Change the 2 to 2.0 to
force floating point in the division, add 1 to each of the end ranges,
and use the modulo operator to do the comparison and it works:
howhigh= input ("How high should I check?")
for number in range (1,howhigh + 1):
factorsum = 0
halfnumber=number / 2.0
for checking in range (1, halfnumber + 1):
if number % checking == 0:
factorsum = factorsum + checking
if number == factorsum:
print number
How high should I check?50
6
28
On recent releases of Python (2.1+, I believe) you can also add the line:
from __future__ import division
to your program, which will make division behave the way you were expecting.
More information about the Python-list
mailing list