Problem 9 : Special Pythagorean triplet

*Difficulty: Easy

Problem:

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.

How to solve:

for a from 1 to 998

—-for b from a+1 to 999

——–for c from b+1 to 1000

————if a+b+c equals 1000 and a*a+b*b equals c*c

—————-print out abc

Took 15 ms

Implementation: Java

public class Problem9 {

        public static void main(String[] args) {

                for(int a = 1; a <= 998; ++a) {

                        for(int b = a+1; b <= 999; ++b)

                                for(int c = b+1; c <= 1000; ++c) {

                                        if(a+b+c == 1000 && a*a+b*b==c*c) {

                                                System.out.println(a + ” “ + b + ” “ + c + ” – “ + a*b*c);

                                        }

                                 }

                        }

               }

        } //end main

}

Advertisements