Kjell Vos Portfolio!

I post about code here and other IT related subject matter.

Project Euler problem 1 Java

In this blog post we will be taking a look Project Euler problem 1 in Java. Project Euler is a great website to train mathematics and programming, You can choose a language and figure out some of the problems. Just know the first problems are the easiest and later ones more difficult.

The first problem of project Euler found here, below is the problem for quick lookup.

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.

-Project Euler problem #1

It’s quite a simple problem, You can get some good use out of the modulo operator.

You start by defining an integer variable set at 3, since no number below 3 can be a multiple of 3. Then we start a loop from the earlier mentioned 3 till 999 since the problem says below 1000. We use the loop counter to check with modulo whether it’s a multiple of 5 or 3, if it is we add it to the sum.

int sum = 0;
for (int i = 3; i < 1000; i++){
    if (i % 3 == 0 || i % 5 == 0) {
        sum += i;
    }
}
System.out.println(sum);

Once the loop finishes we print the sum and we are done!

The solution/output is: 233168.

Check out the ‘Project Euler in Java’ page for more solutions!

Link to github.

That was Project Euler problem 1 in Java!

Leave a Reply

Your email address will not be published. Required fields are marked *.

*
*
You may use these <abbr title="HyperText Markup Language">HTML</abbr> tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.