Pythagorean Proposition

Description

One day, WXYZ got a wooden stick, he wanted to split it into three sticks and make a right-angled triangle. You will be given the length of the stick, and your task is to help WXYZ to find all different right triangles that can be made. 

Input

 The first line of the input is a positive integer T. T is the number of test cases followed. Each test case contains a integer L (1<=L<=1000), representing the length of the stick.

Output

 For each test case, output all different right-angled triangles. For each triangle, output one line containing three integers X Y Z, (1<=X<=Y<=Z, X*X+Y*Y=Z*Z). All triangles are sorted in lexicographical order.

Output a blank line after each test case.


題目解釋:對於給定長度,求解該長度是否能夠分成三條邊組成一個直角三角形

解題思路:使用暴力搜索~使用的過程中有一些小技巧:

(1)由於三角形的任何一條邊都小於周長的一半,因此對於L的範圍爲 1<= L <= 10001,完全可以考慮邊的範圍在500以內。因此預先求出每個數的平方存在數組裏面,只需要一個長度爲500的數組

(2)不可能存在兩條邊相同的邊,因爲對於等腰直角三角形,周長必定包含根號二,因爲輸入的是整數,可以排除兩條邊相同的情況。第一個for循環爲i,那麼第二個for循環便可以爲i+1。

#include <iostream>
#include <string.h>
#include <math.h>
using namespace std;
int power[500];
int main(int argc, const char * argv[]) {
    // insert code here...
    int T;
    for (int i = 0; i < 500; i++) {   // 預先存儲所有數的平方於數組之內
        power[i] = i * i;
    }
    cin >> T;
    while (T > 0) {
        int len = 0;
        cin >> len;
        int mx = len/2;              // 三角形的任一條邊一定小於周長的一半
        for (int i = 1; i < mx; i ++) {
            for (int j = i+1 ; j < mx; j ++) {
                int k = len - i - j;
                if (power[i] + power[j] == power[k]) {
                    cout << i << " "<< j << " " << k << endl;
                }
            }
        }
        cout << endl;
        T--;
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章