참고: Special Pythagorean triplet Problem 9
아래는 문제 해결에 도움되는 유효한 (정수론의 어떠헌) 정리도 사용하지 않고,
단순히 중첩된 for 반복문을 사용한 (이해하기 쉬운) C# 소스와 그 실행 결과이다.
C# 소스:
// Filename: PainSolutionEulerProjectNum9.cs
//
// Compile: csc PainSolutionEulerProjectNum9.cs
//
// Execute: PainSolutionEulerProjectNum9
//
// See: https://projecteuler.net/problem=9
using System;
namespace GeneralCommandLineApp
{
class Program
{
static void Main(string[] args)
{
int c;
for (int a = 1; a <=1000/3; a++)
{
for (int b = a; a + b < 1000; b++)
{
c = 1000 - a - b;
if (a*a + b*b == c*c && a + b > c) {
Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c);
Console.WriteLine("And so a + b + c = {0} + {1} + {2} = {3}", a, b, c, a + b + c);
Console.WriteLine("So their product is a*b*c = {0}*{1}*{2} = {3}", a, b, c, a*b*c);
Console.WriteLine("Primitive Pythagorean triplet:");
Console.WriteLine();
int a2, b2, c2;
a2 = a/25;
b2 = b/25;
c2 = c/25;
int g = (int) gcd(a, b, c);
Console.WriteLine(" g = gcd({0}, {1}, {2}) = {3}", a, b, c, g);
Console.WriteLine(" a/g = {0}, b/g = {1}, c/g= {2}", a/g, b/g, c/g);
Console.WriteLine(" {0}, {1}, {2}", a2, b2, c2);
Console.WriteLine(" {0}^2 + {1}^2 = {3} + {4} = {5} = {2}^2", a2, b2, c2, a2*a2, b2*b2, c2*c2);
}
}
}
}
static Int64 gcd(Int64 x, Int64 y, Int64 z)
{
Int64 w = EuclidGCD(x, y);
Int64 v = EuclidGCD(w, z);
return v;
}
static Int64 EuclidGCD(Int64 x, Int64 y)
{
Int64 a, b, r;
a = x < 0 ? -x : x;
b = y < 0 ? -y : y;
r = b;
while (r > 0) {
b = a % r;
a = r;
r = b;
}
return a;
}
}
}
실행 결과:
a = 200, b = 375, c = 425
And so a + b + c = 200 + 375 + 425 = 1000
So their product is a*b*c = 200*375*425 = 31875000
Primitive Pythagorean triplet:
g = gcd(200, 375, 425) = 25
a/g = 8, b/g = 15, c/g= 17
8, 15, 17
8^2 + 15^2 = 64 + 225 = 289 = 17^2