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

Project Euler #1 Sum of multiples of 3 and 5

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
projectmultipleseulersumand

Problem

Given:


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. Find the sum of all the multiples of 3 or 5 below 1000.

Solution:

class Main {
  public static int sumMupltiple(int num, int limit) {
      int numOfMulitples = (limit - 1) / num;
      return num * (numOfMulitples * (numOfMulitples + 1) / 2);
  }

  public static void main(String[] args) {
    System.out.println(
        sumMupltiple(3, 1000) + sumMupltiple(5, 1000) - sumMupltiple(15, 1000));

  }
}


Is there a clearer approach for Java?

Solution

Meta comments

Is your intention to create a separate Java program for each of the hundreds of Project Euler problems? If you plan on completing more than a handful of them, I would recommend finding a way to consolidate your solutions to all problems into a single program. You will find a significant amount of overlap between certain questions, so being able to create "helper" routines will benefit you greatly. Consider adding in some testing, validation, and timing framework to make sure your results are correct and being solved within a reasonable amount of time (i.e., PE's suggested 1-minute duration).

Algorithmic Comments

As this is a code review, and not an algorithm review, and because I don't want to spoil yours or anyone else's Project Euler experience, I'll keep this brief. Your algorithm is good; you've already used the closed-form equation for these triangle numbers and done some math. You can actually take the math a step further, but then the programming is trivialized and entirely problem #1-specific.

Code Comments

Creating the general sumMultiple() routine is good, as it is general enough to probably prove useful later on.

I would highly recommend factoring this line into its own problem001() subroutine:

sumMupltiple(3, 1000) + sumMupltiple(5, 1000) - sumMupltiple(15, 1000));


Then in your main() function, you need only do:

System.out.println(problem001());


And the self-documenting nature of that naming scheme makes it pretty clear that you are printing the result of problem 001. It might seem a little silly in this case, but not all problems will be one-liners, and consistency is probably better than brevity in this case.

If you do decide to take some of my "meta comments" advice later, it will be even easier to organize your program.

Code Snippets

sumMupltiple(3, 1000) + sumMupltiple(5, 1000) - sumMupltiple(15, 1000));
System.out.println(problem001());

Context

StackExchange Code Review Q#104737, answer score: 7

Revisions (0)

No revisions yet.