patternjavaMinor
Project Euler - Problem 1 Multiples of 3 and 5 (Java)
Viewed 0 times
problemjavaprojectmultipleseulerand
Problem
I consider myself a beginner at Java but this question was an easy one. My only concern is if there is a more efficient way to write this program. I'm very open minded. I don't care how advanced your answer is, I'm willing to learn.
public static void main(String[] args) {
long limit = 1000;
long sum = sumOfMultiples(3,limit) + sumOfMultiples(5,limit) - sumOfMultiples(15,limit);
}
public static long sumOfMultiples(long number, long limit){
long sum = 0;
long add = number;
for(; add < limit; add+=number){
sum += add;
}
return sum;
}Solution
You used the inclusion-exclusion principle here…
… which is good. The name of the function
There is a way to compute
$$ 1 + 2 + 3 + \ldots + n = \frac{n(n+1)}{2}$$
you can derive a formula for
$$ k + 2k + 3k + \ldots + nk = k \frac{n(n+1)}{2} $$
sumOfMultiples(3,limit) + sumOfMultiples(5,limit) - sumOfMultiples(15,limit);… which is good. The name of the function
sumOfMultiples(…) is pretty clear. (The only uncertainty is whether it includes or excludes the upper bound. JavaDoc would help in that regard.)There is a way to compute
sumOfMultiples() in constant time. Since$$ 1 + 2 + 3 + \ldots + n = \frac{n(n+1)}{2}$$
you can derive a formula for
$$ k + 2k + 3k + \ldots + nk = k \frac{n(n+1)}{2} $$
Code Snippets
sumOfMultiples(3,limit) + sumOfMultiples(5,limit) - sumOfMultiples(15,limit);Context
StackExchange Code Review Q#140695, answer score: 3
Revisions (0)
No revisions yet.