Problem 9(Special Pythagorean triplet)
Problem 9(Special Pythagorean triplet)
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
In Python:
import math
import time
start_time=time.time()
for i in range(1,334):
for j in range(i,500):
k = math.sqrt(pow(i,2)+pow(j,2))
if k.is_integer() and i+j+k==1000:
print(i, j, k, i*j*k)
else:
pass
print(time.time() - start_time,"seconds")
Run time: 0.23833203315734863 seconds
In Java:
//PE9 Special Pythagorean triplet
package project_euler;
public class Euler9 {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
double k = 0;
for (int i = 1; i < 334; i++) {
for (int j = i; j < 500; j++) {
k = Math.sqrt(Math.pow(i, 2) + Math.pow(j, 2));
if (k == (int)k && i+j+k == 1000) {
System.out.println(i * j * k);
}
}
}
long endTime = System.currentTimeMillis();
System.out.println((double)(endTime - startTime)/(double)1000 + "seconds");
}
}
Run time: 0.007seconds
solution: 31875000
[from Project Euler: https://projecteuler.net/problem=9]