Rektyyy
Rektyyy

Reputation: 51

Python - sum of multiples of 3 or 5 below 1000

The problem sounds like this: "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."

I have written some code below and I'm confused as to why it doesn't work

s1 = 0
s2 = 0
for i in range(0,1000,3):
    s1 = s1 + i
for i in range(0,1000,5):
    s2 = s2 + i
suma = s1 + s2
print(suma)

On top of this, I tried assigning the value of 0 to all the variables at once:

suma, s1, s2 = 0
#the rest of the code here

And I'm getting the following error: TypeError: cannot unpack non-iterable int object

How do I assign everything at once? Do I even need to assign every variable to 0 in order for my code to work or is it similar to Turbo Pascal where every int variable automatically gets assigned 0?

Upvotes: 1

Views: 1008

Answers (3)

Avinash Gunda
Avinash Gunda

Reputation: 1

def get_multiples(num):
    if num%3==0 or num%5==0:
        return num

n=int(input("Enter a number = "))
multiples = sum(set(list(filter(get_multiples, list(range(n))))))
print(multiples)

Upvotes: -1

cdlane
cdlane

Reputation: 41925

As Pythonic as @MarkMeyer's answer may be, let's fix your original code to produce the correct result. (And assign the value 0 to all the variables at once.)

s1 = s2 = s3 = 0

for i in range(0, 1000, 3):
    s1 += i

for i in range(0, 1000, 5):
    s2 += i

for i in range(0, 1000, 3 * 5):
    s3 += i

suma = (s1 + s2) - s3

print(suma)

Upvotes: 2

Mark
Mark

Reputation: 92481

Counting each range one at a time counts the numbers that are multiples of both 5 and 3, like 15 and 30, twice.

A more python way to do this would be to imagine taking the range as a sequence and filtering out all numbers that don't meet your criteria. Then sum up the sequence. For multiples of 5 or 3 (or both), that criteria might look like:

n % 3 == 0 or n % 5 == 0

% produces the remainder divided by the following number. For any n this is only true if it is a multiple of 5 or 3. You can use that to filter the range and sum:

sum(n for n in range(10) if n % 3 == 0 or n % 5 == 0)
# 23

This works because the inner bit makes an iterator of just the values you want:

[n for n in range(10) if n % 3 == 0 or n % 5 == 0]
# [0, 3, 5, 6, 9]

And summing that with the builtin function sum() gives the correct answer.

Also the error you are getting is because this format of assignment tries to unpack several values:

a, b, c = [1, 2, 3] # works
a, b, c = 10 # error -- not enough values.

Upvotes: 3

Related Questions