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. I have the following code but the answer do
Think declaratively - what you want to do, rather than how you want to do.
In plain language, it boils down to exactly what the problem asks you to do:
In LINQ, it looks like:
Enumerable.Range(1, 1000)
.Where(x => (x % 3 == 0) || (x % 5 == 0))
.Aggregate((accumulate, next) => accumulate += next);
Now, you can convert this into an iterative solution - but there is nothing wrong with using a declarative solution like above - because it is more clear and succinct.
Just as an improvement you might want to avoid the loop altogether :
multiples of 3 below 1000 form an AP : 3k where k in [1, 333]
multiples of 5 below 1000 form an AP : 5k where k in [1, 199]
If we avoid multiples of both 3 and 5 : 15k where k in [1, 66]
So the answer is : 333*(3+999)/2 + 199(5+995)/2 - 66*(15+990)/2 = 2331
68
Why you might want to do this is left to you to figure out.
Here's a python one-liner that gives the correct answer (233168):
reduce( lambda x,y: x+y, [ x for x in range(1000) if x/3.0 == int( x/3.0 ) or x/5.0 == int( x/5.0 ) ] )
I attempt the Project Euler #1: Multiples of 3 and 5. And got 60 points for that.
private static long euler1(long N) {
long i, sum = 0;
for (i = 3; i < N; i++) {
if (i % 3 == 0 || i % 5 == 0) {
sum += i;
}
}
return sum;
}
I use Java for it and you can use this logic for C. I worked hard and find an optimal solution.
private static void euler1(long n) {
long a = 0, b = 0, d = 0;
a = (n - 1) / 3;
b = (n - 1) / 5;
d = (n - 1) / 15;
long sum3 = 3 * a * (a + 1) / 2;
long sum5 = 5 * b * (b + 1) / 2;
long sum15 = 15 * d * (d + 1) / 2;
long c = sum3 + sum5 - sum15;
System.out.println(c);
}