该计划的目标是使用欧几里德公式(a = m ^ 2 -n ^ 2,b = 2mn,c = m ^ 2)找出每个值(a,b,c)小于500的所有毕达哥拉斯三元组+ n ^ 2.)所以这是我的代码。
int main()
{
clock_t start = clock()/ (CLOCKS_PER_SEC/1000);
for (int m = 1; m <= 500; m++)
{
for (int n = 1; n <= 500; n++)
{
int a = (m*m)-(n*n);
int b = 2*m*n;
int c = (m*m)+(n*n);
if (m > n && a + b == c)
{
cout << a << " + " << b << " = " << c << endl;
}
}
}
clock_t finish = clock()/ (CLOCKS_PER_SEC/1000);
cout << "completed in " <<clock() << " ms";
return 0;
}
我试过这个,我的输出什么都没有。我认为它的工作方式是:对于小于/等于500且从1开始的每个整数,每次加1到m。同样的交易n。然后将这些值插入到公式中,如果a + b == c,则打印这些值,从而找到我的三元组。但我没有得到任何输出。
答案 0 :(得分:3)
a + b = (m^2 + 2mn - n^2) = (m+n)^2 - 2n^2
c = m^2 + n^2 = (m+n)^2 - 2mn
您需要a + b = c
--> 2n^2 = 2mn
--> m = n
由于您还需要m > n
,因此无法找到任何解决方案。
答案 1 :(得分:0)
你的情况错了:你想要
(m ^ 2 - n ^ 2)+ 2mn =(m ^ 2 + n ^ 2)
(m-n)^ 2 = m ^ 2 + n ^ 2
但对于n > 0
,您将始终存在以下严格的不等式:
(m-n)^ 2&lt; m ^ 2&lt; m ^ 2 + n ^ 2
根据维基百科,你想检查平方和是否相等 -
(a ^ 2 + b ^ 2)== c ^ 2
答案 2 :(得分:0)
您在实施中犯了一些错误(请参阅下面的修复):
int main()
{
for (int n = 1; n <= 500; ++n) // note the swap for the loops
{
for (int m = n + 1; m <= 500 && (m*m + n*n) <= 500; ++m) // note that m starts at n + 1
{
int a = (m*m)-(n*n);
int b = 2*m*n;
int c = (m*m)+(n*n);
// Euclid already proved this, so there is no need to test it.
std::cout << a << " + " << b << " = " << c << std::endl;
}
}
return 0;
}
m > n
,因此无需检查不符合该条件的值(a + b) == c
无论如何都无法运行。公式为a^2 + b^2 = c^2
- 这并不意味着a + b = c
。答案 3 :(得分:0)
int main()
{
clock_t start = clock()/ (CLOCKS_PER_SEC/1000);
for (int n = 1; n <= 500; n++)
{
for (int m = n+1; m <= 500; m++)
{
int a = (m*m)-(n*n);
int b = 2*m*n;
int c = (m*m)+(n*n);
if ((a*a) + (b*b) == (c*c) && c <= 500)
{
cout << a << " + " << b << " = " << c << endl;
}
}
}
clock_t finish = clock()/ (CLOCKS_PER_SEC/1000);
cout << "completed in " <<clock() << " ms";
return 0;
}
这样程序就不会像我遇到问题一样长。谢谢大家!