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.

問 9 「特別なピタゴラス数」

ピタゴラス数(ピタゴラスの定理を満たす自然数)とは a < b < c で以下の式を満たす数の組である.

a2 + b2 = c2

例えば, 32 + 42 = 9 + 16 = 25 = 52 である.

a + b + c = 1000 となるピタゴラスの三つ組が一つだけ存在する.

これらの積 abc を計算しなさい.

fn main() {
    let mut ans = None;
    'exploration: for m in 2..=(499f32.sqrt() as u32) {
        for n in 1..m {
            let a = m * m - n * n;
            let b = 2 * m * n;
            let c = m * m + n * n;
            if a + b + c == 1000 {
                ans = Some(a * b * c);
                break 'exploration;
            }
        }
    }

    println!("{:?}", ans);
    assert_eq!(ans.unwrap(), 31875000);
}
package main

import (
	"fmt"
	"math"
	"testing"
)

func Example() {
	var ans uint32
Exploration:
	for m := uint32(2); m <= uint32(math.Sqrt(float64(499))); m++ {
		for n := uint32(1); n < m; n++ {
			a := m*m - n*n
			b := 2 * m * n
			c := m*m + n*n
			if a+b+c == 1000 {
				ans = a * b * c
				break Exploration
			}
		}
	}
	fmt.Println(ans)
	// Output: 31875000
}
→ Go playground
function assert(condition: any, msg?: string): asserts condition {
  if (!condition) {
    throw new Error(msg);
  }
}

let ans = 0;
exploration:
for (let m = 2; m <= (Math.sqrt(499) | 0); m++) {
  for (let n = 1; n < m; n++) {
    const a = m * m - n * n;
    const b = 2 * m * n;
    const c = m * m + n * n;
    if (a + b + c === 1000) {
      ans = a * b * c;
      break exploration;
    }
  }
}
console.log(ans);
assert(ans === 31875000);
→ TypeScript playground