Project Euler - Problem 1 Multiples of 3 and 5 (Java) 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 &lt; limit; add+=number){
        sum += add;
    }

    return sum;
}
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} $$