이경수 선생님의 수학실험실

Problem 9(Special Pythagorean triplet) 본문

Project Euler

Problem 9(Special Pythagorean triplet)

(이경수) 2019. 2. 9. 13:42

Problem 9(Special Pythagorean triplet)

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.



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]






'Project Euler' 카테고리의 다른 글

Problem 11(Largest product in a grid)  (0) 2019.02.10
Problem 10(Summation of primes)  (0) 2019.02.09
Problem 8(Largest product in a series)  (0) 2019.02.09
Problem 7(10001st prime)  (0) 2019.02.08
Problem 6(Sum square difference)  (0) 2019.02.08
Comments