2017-06-03

Project Euler Problem 1

"If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000."

For this problem I think I'll need the syntax for for-loop and if-statement. From Python Wiki:

for x in range(0, 3):
    print "We're on time %d" % (x)

What to notice here is that the print command is not written as a function. This is probably because the page is written for Python 2.x and not Python 3.x that I'm running. To make it run, I'll rewrite it as a function with parentheses.

for x in range(0, 3):
    print("We're on time %d" % (x))

This returns:

We're on time 0
We're on time 1
We're on time 2

Process finished with exit code 0

What does %d do? According to Stack Overflow %d is a placeholder for numbers and %s is a placeholder for strings. I.e. %d is where the variable x will be output. Try and see!

Now to the Euler Project Problem 1 and to the problem with documenting programming progress. Of course I didn't succeed on the first try and I did learn something useful. What I did wrong (failed maybe 6-7 times) was that I used "sum=+x" to add up the values. After trying "sum = sum + x" it worked like a charm and I got the correct answer. Isn't it weird that "sum=+x" didn't work? Yes and no, I was thinking correctly but got it wrong. The correct syntax for this operation is to have the + before =, i.e. "sum+=x" works. This is my code:

sum = 0
for x in range(0, 1000):
    if x%3==0 or x%5==0:
        sum+=x

print('%s %d' % ("Sum: ", sum))

/Ludvig

No comments:

Post a Comment