First off, I apologize for my inaccurate vocabulary. I am an absolute ground-zero beginner. Anyways, I am attempting to solve this problem:
http://projecteuler.net/problem=1
To be brief, I’m trying to write a script that will find the sum of all the multiples of 3 or 5 below 1000.
My (extremely basic) approach was with this program:
##Multiples of 3
x = range(3, 1000, 3)
##Multiples of 5
y = range(5, 1000, 5)
a = sum(x)
b = sum(y)
n = a + b
print n
I realized that this was wrong because there are numbers like 15 that are included twice (it’s a multiple of both 5 and 3).
So is there a way to fix this or am I approaching this problem from a completely wrong angle?
Or do I need to just study more before I try solving this problem?
I also apologize if this has been explained in a previous post, but I looked around for a bit.
It is called inclusion exclusion principle so you can do like
but beauty is in using generators or list comprehensions
Where % is modulo and is remainder in integer devision.
Nice thing about this is that codes reads so fluently and is direct translation of rules and can be read from left to right.
Both algorithms run times depends on n in this case is 1000. If n would be for instance 1000000000 you would have to wait for long time to complete. If you apply little mathematics you can find out that
is actually arithmetic progression and total of this can be calculated in constant time no matter how big n is. http://en.wikipedia.org/wiki/Project_Euler#Example_problem_and_solutions