qwerty
qwerty

Reputation: 991

How to find the sum of all the multiples of 3 or 5 below 1000 in Python?

Not sure if I should've posted this on math.stackexchange instead, but it includes more programming so I posted it here.

The question seems really simple, but I've sat here for at least one hour now not figuring it out. I've tried different solutions, and read math formulas for it etc but it won't gives me the right answer when coding it! I made two different solutions for it, which both gives me the wrong answer. The first solution gives me 265334 while the second one gives me 232169. The answer is 233168, so the second solution is closer.

I should mention this is a question from Project Euler, the first one to be precise.

Here's my code. Any ideas what's wrong?

nums = [3, 5]
max = 999

result = 0
for num in nums:
    for i in range(1,max):
        if num*i < max:
            result += num*i
print result


result = 0
for i in range(0,max):
    if i%3 == 0 or i%5 == 0:
        result += i

print result

Upvotes: 11

Views: 85460

Answers (20)

ajith acharya
ajith acharya

Reputation: 1

Check this one:

target = 1000
n, m, x = target//3, target//5-1, target//15
t3 = int((3*n*(n+1))/2) #sum of multiple of 3 for Nth value 
t5 = int(5/2*m*(m+1)) ##sum of multiple of 5 for Nth value
t15 = int((15*x*(x+1))/2) #sum of multiple of 3 and 5 for nth value

print(t3+t5-t15)

Upvotes: 0

OwenIT
OwenIT

Reputation: 11

total = 0

maxrange = input("Enter the maximum range") #Get the maximum range from the keyboard print("")

max = int(maxrange)

for i in range (0,max): if i%3 == 0 or i%5 ==0: total = total +i

print (total)

Upvotes: 1

user3770705
user3770705

Reputation: 21

result = 0
for i in range(0,1000):
    if (i % 3 == 0 or i % 5 == 0):
        print i
        result = result + i
print result

Output:

0
3
5
6
9
.
.
.
993
995
996
999
233168

Upvotes: 2

PhysicsLot
PhysicsLot

Reputation: 1

Here is the code:

count = 1000
m = [3, 5, 3*5]
result = 0
Sum = 0
for j in m:
    result = 0
    for i in range(count):
        if i*j < 1000:
            result = result + i*j
        elif i == (count - 1):
            if j < 15:
                Sum = result + Sum
            elif j == 15:
                Sum = Sum - result
                print(Sum)

Upvotes: 0

Manon Collins
Manon Collins

Reputation: 1

I had to do it in range 1 , 100

This is how I did it.

For i in range(1,100):

If i ÷ 3 == 0 and i ÷ 5 == 0:

 print(i) 

So with 1000 you just change the 100 to 1000

I had to find the multiples of 3 and 5 within 100 so if you need 3 or 5 just change it to or and it will give you more answers too. I'm just starting to learn so correct me if I'm wrong

Upvotes: 0

Umut Tolek
Umut Tolek

Reputation: 1

I know it was 7 years ago but I wanna share my solution to this problem.

x= set()
for i in range(1,1001):
    if (i % 3) == 0:
        x.add(i)

for j in range(1,1001):
    if (j % 5) == 0:
        x.add(j)

print(sum(x))

Upvotes: 0

Umesh Yadav
Umesh Yadav

Reputation: 1210

t = int(input())
for a in range(t):
n = int(input().strip())
sum=0
for i in range(0,n):
       if i%3==0 or i%5==0:
            sum=sum+i
print(sum)

Upvotes: 1

Anuj Kulkarni
Anuj Kulkarni

Reputation: 137

I think only the last few lines from your code are important. The or statement is the key statement in this code. Also rater than setting the max value to 999, you should set it to 1000 so that it will cover all values. Here is my code.

    ans=0
    for i in range(1,1000):
        if(i%3==0 or i%5==0):
            ans += i
    print(ans)
    input('press enter key to continue');#this line is only so that the screen stays until you press a key

Upvotes: 1

Jitendra Bhalothia
Jitendra Bhalothia

Reputation: 407

count = 0

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

print(count)

Upvotes: 0

Shreyansh Mehta
Shreyansh Mehta

Reputation: 1

this is my solution

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

Upvotes: 0

simsosims
simsosims

Reputation: 285

I know this is from 6 years ago but I just thought id share a solution that found from a math formula that I thought was interesting as it removes the need to loop through all the numbers.

https://math.stackexchange.com/a/9305

def sum_of_two_multiples(nums, maxN):
    "takes tuple returns multiples under maxN (max number - 1)"
    n1, n2 = nums = nums[:2]
    maxN -= 1
    def k(maxN, kx):
        n = int(maxN / kx)
        return int(kx * (0.5 * n * (n+1)))

return sum([k(maxN, n) for n in nums]) - k(maxN, n1*n2)

Outputs the follows

print(sum_of_two_multiples((3,5), 10))
# 23
print(sum_of_two_multiples((3,5), 1000))
# 233168
print(sum_of_two_multiples((3,5), 10**12))
# 233333333333166658682880

Upvotes: 2

Dave
Dave

Reputation: 9085

There are floor(999/3) multiples of 3, floor(999/5) multiples of 5, and floor(999/15) multiples of 15 under 1000.

For 3, these are: 3 + 6 + 9 + 12 +... + 999 = 3 * (1 + 2 + 3 + 4 +...+333)

= 3 * (333 * 334 / 2) because the sum of the integers from 1 to k is k*(k+1)/2.

Use the same logic for the sum of multiples of 5 and 15. This gives a constant time solution. Generalize this for arbitrary inputs.

Upvotes: 1

Emily Fotopoulou
Emily Fotopoulou

Reputation: 1

here is my solution:

for n in range(100):
    if n % 5==0:
        if n % 3==0:
        print n, "Multiple of both 3 and 5"    #if the number is a multiple of 5, is it a multiple of 3? if yes it has has both.

    elif n % 5==0:
        print n, "Multiple of 5"

    elif n % 3==0:
        print n, "Multiple of 3"

    else:
        print n  "No multiples"

Upvotes: 0

Alexey Bogomolov
Alexey Bogomolov

Reputation: 135

You can also use functional programming tools (filter):

def f(x):
    return x % 3 == 0 or x % 5 == 0
    filter(f, range(1,1000)) 
print(x)

Or use two lists with subtraction of multiples of 15 (which appears in both lists):

sum1 = []
for i in range(0,1000,3):
    sum1.append(i)
sum2 = []
for n in range(0,1000,5):
    sum2.append(n)
del sum2[::3] #delete every 3-rd element in list
print(sum((sum1)+(sum2)))

I like this solution but I guess it needs some improvements...

Upvotes: 0

Zach Kelling
Zach Kelling

Reputation: 53879

You are overcomplicating things. You just need a list of numbers that are multiples of 3 or 5 which you can get easily with a list comprehension:

>>> [i for i in range(1000) if i % 3 == 0 or i % 5 == 0]

Then use sum to get the total:

>>> sum([i for i in range(1000) if i % 3 == 0 or i % 5 == 0])
<<< 233168

Or even better use a generator expression instead:

>>> sum(i for i in range(1000) if i % 3 == 0 or i % 5 == 0)

Or even better better (courtesy Exelian):

>>> sum(set(list(range(0, 1000, 3)) + list(range(0, 1000, 5))))

Upvotes: 18

Marc
Marc

Reputation: 514

I know this was 3 months ago but as an experiment because I am new to python I decided to try and combine some of the other people answers and I came up with a method you can pass the max number to and the divisors as a list and it returns the sum:

def sum_of_divisors(below, divisors):
    return sum((n for n in xrange(below) if 0 in (n % d for d in divisors)))

max = 1000
nums = [3, 5]

print sum_of_divisors(max, nums)

Upvotes: 1

pillmuncher
pillmuncher

Reputation: 10162

I like this the most:

def divisibles(below, *divisors):
    return (n for n in xrange(below) if 0 in (n % d for d in divisors))

print sum(divisibles(1000, 3, 5))

Upvotes: 3

Jaanus
Jaanus

Reputation: 16561

max = 1000  # notice this here
result = 0
for i in range(0,max):
if i%3 == 0 or i%5 == 0:
    result += i

print result

This works, but use 1000 for max, so it includes 999 too.

Upvotes: 1

Gabe
Gabe

Reputation: 86848

The problem with your first solution is that it double-counts multiples of 15 (because they are multiples of both 3 and 5).

The problem with your second solution is that it doesn't count 999 (a multiple of 3). Just set max = 1000 to fix this.

Upvotes: 2

Fred Foo
Fred Foo

Reputation: 363858

range(k,max) does not include max, so you're really checking up to and including 998 (while 999 is a multiple of 3). Use range(1,1000) instead.

Upvotes: 6

Related Questions