HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Project Euler - Problem 1 Multiples of 3 and 5 (Java)

Submitted by: @import:stackexchange-codereview··
0
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…

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.