にたまごほうれん草アーカイブ

はてなダイアリーで書いてた「にたまごほうれん草」という日記のアーカイブです。現在は「にたまごほうれん草ブログ」を運営中です。

Problem 9

今日も一つ、解いていくよ。

ピタゴラスの三つ組(ピタゴラスの定理を満たす整数)とはa

Problem 9 - PukiWiki

順番にやっていくだけで充分。二重のfor文から抜けたかったのでgotoを使用。

#include <stdio.h>

#define NUM_MAX 1000

void problem009()
{
    int ans;
    int a, b, c;

    /* solve this problem here */
    a = 1; b = 1; c = 1;
    for (a=1; a<NUM_MAX; a++) {
        for (b=a; b<NUM_MAX-a; b++) {
            c = NUM_MAX - a - b;
            if ((a*a)+(b*b) == c*c) {
                goto answer;
            }
        }
    }

answer:
    ans = a * b * c;
    printf("(a, b, c) = (%d, %d, %d)\n", a, b, c);
    printf("%s: answer = %d\n", __FUNCTION__, ans);
}

int main(int argc, char* argv[]) 
{
    problem009();
    return 0;
}

実行結果

$ ./problem009
(a, b, c) = (200, 375, 425)
problem009: answer = 31875000