我想获得一个列表:右三角的侧面
这是完全整数。(每边小于100)
示例:
//I want these combination to be printed
3, 4, 5
6, 8, 10 |'.
5, 12, 13 12 | '. 13 (Figure is just Example)
. | '.
. |______'.
. 5
// I don't want these
1, 1, 1.414.... |'.
. 1 | '. √ˉ2 = 1.414.... (Figure is just Example)
. | '.
|______'.
1
更新
我喜欢这样:但这是非常繁重的代码(关于优化)
for(int i=1;i<100;i++)
{
for(int j=1;j<100;j++)
{
for(int k=1;k<100;k++)
{
if(i*i + j*j == k*k)
{
//print i, j, k
}
}
}
}
答案 0 :(得分:6)
您正在寻找的是Pythagorean triples。
答案 1 :(得分:3)
// Obvious min is 1, obvious max is 99.
for(int i = 1; i != 100; ++i)
{
// There's no point going beyond the lowest number that gives an answer higher than 100
int max = 100 * 100 - i * i;
// There's no point starting lower than our current first side, or we'll repeat results we already found.
for(int j = i; j * j <= max; ++j)
{
// Find the square of the hypotenuse
int sqr = i * i + j * j;
// We could have a double and do hyp == Math.Round(hyp), but lets avoid rounding error-based false positives.
int hyp = (int)Math.Sqrt(sqr);
if(hyp * hyp == sqr)
{
Console.WriteLine(i + ", " + j + ", " + hyp);
// If we want to e.g. have not just "3, 4, 5" but also "4, 3, 5", then
// we can also here do
// Console.WriteLine(j + ", " + i + ", " + hyp);
}
}
}
答案 2 :(得分:1)
如果您利用每对导管对于斜边只有一个可能值的事实,您可以通过移除最内层循环来改进代码。您可以使用毕达哥拉斯定理计算它,而不是循环找到该值,并测试它是否为整数。
类似的东西:
// compute the hypotenuse
var hypotenuse = Math.Sqrt(i*i + j*j);
// test if the hypotenuse is a whole number < 100
if(hypotenuse < 100 && hypotenuse == (int)hypotenuse)
{
// here's one!
}
您可以做的其他一些改进包括:
答案 3 :(得分:1)
我曾在C#中使用this formula来生成过去的毕达哥拉斯三元组。但该页面上还有许多其他选项。
答案 4 :(得分:0)
相当不错的详尽搜索:
for(i=1;i<100;i++) {
k=i;
for(j=1;k<100;j++) {
while(i*i+j*j<k*k) {
k++;
}
if(i*i+j*j==k*k) {
printf("%d %d %d", i, j, k);
}
}
}
答案 5 :(得分:0)
用声明性语言(Mathematica):
FindInstance[x^2 + y^2==z^2 &&1<=z<=100 && 1<=y<=x<=100, {x, y, z}, Integers,100]