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
count = 0
for i in range(0,1000):
if i % 3 == 0 or i % 5 ==0:
count = count + i
print(count)
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
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.
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.
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
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)