Project Euler – Problem # 9 – Solved with Java & Python

Find the only Pythagorean triplet, {a, b, c}, for which a + b + c = 1000.

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.

**********

The wikipedia page on Pythagorean triple is helpful in solving this problem. Particularly the part about
Euclid’s formula: a = m2 – n2, b = 2mn, c = m2 + n2.

Helpful link:

Pythagorean triplehttp://en.wikipedia.org/wiki/Pythagorean_triple

One Possible Solution: Java


public class Problem_09 {
	public static void main(String [] args){
		for (int n = 1; n < 500; n++) {
			for (int m = (n + 1); m < 500; m ++) {
				int a = (m * m) - (n * n);
				int b = 2 * m * n;
				int c = (m * m) + (n * n);
				if (a + b + c == 1000) {
					int product = a * b * c;
					System.out.format("a = %d" + "b = %d" + "c = %d" + newline, a, b, c);
					System.out.format("Product = %d" + newline, product);
				}
				
			}	
		}	
	}
	public static String newline = System.getProperty("line.separator");
}

One Possible Solution: Python

import math
    
def main():
    """Main program"""
    for n in xrange(1, 500):
        for m in xrange(n + 1, 500):
            a = int(math.pow(m, 2) - math.pow(n, 2))
            b = 2 * m * n
            c = int(math.pow(m, 2) + math.pow(n, 2))
            if a + b + c == 1000:
                product = a * b * c
                print "a = %d, b = %d, c = %d" % (a, b, c)
    print "Product = %d" % (product)

if __name__ == '__main__':
    main()
Advertisements

Project Euler – Problem # 9 – Solved with Go

Find the only Pythagorean triplet, {a, b, c}, for which a + b + c = 1000.

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.

**********

The wikipedia page on Pythagorean triple is helpful in solving this problem. Particularly the part about
Euclid’s formula: a = m2 – n2, b = 2mn, c = m2 + n2.

Helpful link:

Pythagorean triplehttp://en.wikipedia.org/wiki/Pythagorean_triple

One Possible Solution: Go

package main

import "fmt"
import "math"

func main() {
	for n := 1; n < 500; n++ {
		for m := (n + 1); m < 500; m++ {
			a := int(math.Pow(float64(m), 2) - math.Pow(float64(n), 2))
			b := 2 * m * n
			c := int(math.Pow(float64(m), 2) + math.Pow(float64(n), 2))
			if a+b+c == 1000 {
				product := a * b * c
				fmt.Println(a, b, c)
				fmt.Println(product)
			}
		}

	}
}