Kjell Vos Portfolio!

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

Project Euler Problem 9 Java

In this blog post we will be looking at problem 9 of Project Euler and we will program a solution in Java.

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

A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,

a2 + b2 = c2

For example, 32 + 42 = 9 + 16 = 25 = 52.

There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.

-Project Euler problem 9

Let’s summarize the rules.

  • a < b < c
  • a^2 + b^2 = c^2
  • a + b + c = 1000

So let’s start defining the program! We need two for loops. If we make the first for loop ‘a’ and the second ‘b’ we can get c with some math:

c = 1000 – a – b

Because of the last rule where a, b and c add up to 1000. We can then check if a^2 + b^2 = c^2 and if it is print the result.

for (int a = 1; a < 1000 / 3; a++) {
    for (int b = a; b < 1000 / 2; b++) {
        int c = 1000 - a - b;    
        if (a*a + b*b == c*c) {
            System.out.println("a:" + a);
            System.out.println("b:" + b);
            System.out.println("c:" + c);
            System.out.println(a * b * c);
        }
    }
}

There are some optimizations in the loop condition in the 2 for loops. Since a has to be smaller than b and c we can divide the loop condition of loop A by 3 leaving you with a max of 333. The same for loop B where we divide by 2 leaving you with a max of 500. Because of the a < b < c rule you can assume this. We initialize b to the current value of a because of the same rule.

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

Link to github.

That was Project Euler problem 9 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.