[Tutor] Add all natural numbers that are multiples of 3 and 5
Andre Engels
andreengels at gmail.com
Sun Jan 4 01:43:36 CET 2009
On Sun, Jan 4, 2009 at 1:06 AM, Benjamin Serrato
<benjamin.serrato at gmail.com> wrote:
> Hello,
>
> I'm trying to correctly solve the first projecteuler.net problem. The
> question is as so: Find the sum of all the multiples of 3 or 5 below 1000.
>
> I wrote the following program, but the number found is incorrect. I created
> a function that adds multiples of a given number to a global variable until
> the multiples are greater than 1000. The solution I get with my code is
> "1224". This is incorrect, but I am having trouble understanding why my code
> is wrong... it's very simple.
> My code:
>
> #!!/usr/local/bin/python3.0
> #problem1.py
>
> """Lists the sum of all multiples of 3 and 5 less than 1000."""
>
> # Initialize variable 'total'.
> total = 0 # I wanted this to be 'None', is that wrong?
>
> def sumTotal(multiple):
> global total # Brings total into the local scope so it
> # can be written to.
> n = 2
> while multiple < 1000:
> total = total + multiple
> multiple = multiple * n
> n = n + 1 # I wanted this to be += but I'm not sure
> # that is right.
>
> # Now I call the function with the two arguments I need, 3
> # and 5. Since total is a global variable it retains its value
> # at the end of the first function call, the next call adds to
> # the total value. Thus print(total) should give me the correct
> # value.
>
> sumTotal(3)
> sumTotal(5)
>
> print(total)
>
> -----
> I think I have made a mistake with scope. Or some other syntactic error,
> because I don't see anything wrong with the code. Please make it obvious for
> me.
There is an error with the code. The line
multiple = multiple * n
is not doing what you want it to do.
See what is happening each time you go through this line:
first time:
* multiple = 3
* n = 2
* multiple changed to 6
second time:
* multiple = 6
* n = 3
* multiple changed to 18
third time:
* multiple = 18
* n = 4
* multiple changed to 72
etcetera
You will have to keep the number to multiply by in a separate variable
to avoid this.
Apart from that, I think your usage of a global variable total,
although correct, is ugly and error-prone. I would do away with a
global variable total, add a local variable total, and end defSum with
"return total".
Then the main body can be changed to:
print (sumTotal(3) + sumTotal(5))
--
André Engels, andreengels at gmail.com
More information about the Tutor
mailing list