Project Euler problem:
If we list all the natural numbers below
10
that are multiples of3 or 5
, we get3, 5, 6 and 9
Your solution with for-loop will be O(n).
I found a more generic solution O(1).
Here we can use another multiplies, even non-primes.
#include
long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
long lcm(long a, long b) {
return a / gcd(a, b) * b;
}
long sumMultiple(long mult, long to) {
to = to / mult;
to *= to + 1;
return (to >> 1) * mult;
}
long calc(long a, long b, long n) {
n--;
return sumMultiple(a, n) + sumMultiple(b, n) - sumMultiple(lcm(a,b), n);
}
int main() {
int n = 1000;
printf("Sum of multiplies of 3 and 5 is %ld\n", calc(3,5,n));
return 0;
}