<Sicily>Pythagorean Proposition
一、题目描述
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.
二、输入
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.
三、输出
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.
例如:
输入:
3
40
50
60
输出:
8 15 17
10 24 26
15 20 25
四、解题思路
这道题相对比较水,主要是从1开始遍历两条直角边的平方和是否等于第三边平方。
总边长为:perimeter
假设最短那条直角边shortHEdge初始值为1;
长的那条直角边longHEdge初始值为1/2perimeter(直角边比斜边短)
斜边longLEdge=perimeter-shortHEdge-longHEdge
判断两直角边的平方和quadraticSum跟斜边平方比。
如果quadraticSum>longLEdge^2,长的直角边-1;
如果quadraticSum
五、代码
#include<iostream>
using namespace std;
int main()
{
int times;
cin >> times;
while(times--)
{
int perimeter, shortHEdge, longHEdge, longLEdge;
long long quadraticSum;
cin >> perimeter;
shortHEdge = 1; //短的直角边
longHEdge = perimeter / 2; //长的直角边
while(shortHEdge <= longHEdge) //长的直角边要保持大于等于短的直角边
{
longLEdge = perimeter - longHEdge - shortHEdge; //斜边长度
quadraticSum = (shortHEdge * shortHEdge) + (longHEdge * longHEdge); //两"直角"边和
if(quadraticSum < longLEdge * longLEdge) {shortHEdge++;} //两"直角"边和小于斜边
else if(quadraticSum > longLEdge * longLEdge) {longHEdge--;} //两"直角"边和大于斜边
else {cout << shortHEdge << " " << longHEdge << " " << longLEdge << endl; shortHEdge++;} //两直角边和等于第三边
}
cout << endl;
}
return 0;
}