所以我需要帮助计算毕达哥拉斯三元组,基本上我希望输出看起来像这样:
3 4 5
5 12 13
6 8 10
7 24 25
ETC。
我需要计算部分的帮助,并确保我没有重复(即5 12 13和12 5 13)。
思考?有人能引导我朝着正确的方向前进吗?
这是我到目前为止的代码:
package cs520.hw1;
public class Triples {
public static void main(String[] args)
{
int x1, x2, x3;
for(x1 = 1; x1 < 100; x1++)
{
for(x2 = 1; x2 < 100; x2++)
{
for(x3 = 1; x3 < 100; x3++)
{
int a= x1, b=x2, c=x3;
if((Math.sqrt(a) + Math.sqrt(b)) == Math.sqrt(c))
{
if(a < b)
{
System.out.println(x1 +" "+ x2 +" "+ x3);
}
}
}
}
}
}
}
答案 0 :(得分:0)
您需要将对Math.sqrt(n)
的调用更改为Math.pow(n, 2)
,其中n = a,b,c。
因此,代码变为
package cs520.hw1;
public class Triples {
public static void main(String[] args)
{
int x1, x2, x3;
for(x1 = 1; x1 < 100; x1++)
{
for(x2 = 1; x2 < 100; x2++)
{
for(x3 = 1; x3 < 100; x3++)
{
int a= x1, b=x2, c=x3;
if((Math.pow(a, 2) + Math.pow(b, 2)) == Math.pow(c, 2))
{
if(a < b)
{
System.out.println(x1 +" "+ x2 +" "+ x3);
}
}
}
}
}
}
}
答案 1 :(得分:0)
示例代码:
public class QuickTester {
// Change MAX to whatever value required
private static final int MAX = 25;
public static void main(String[] args) {
int a, b, c;
for(a = 1; a < MAX; a++)
{
for(b = a; b < MAX; b++)
{
for(c = b; c < MAX; c++)
{
if((Math.pow(a, 2) + Math.pow(b, 2))
== Math.pow(c, 2))
{
System.out.printf("%d %d %d\n",
a, b, c);
}
}
}
}
}
}
输出(MAX为25而不是100):
3 4 5
5 12 13
6 8 10
8 15 17
9 12 15
12 16 20
注意:强>
答案 2 :(得分:0)
public class Triplets {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int a, b, c;
System.out.println("Enter the value of n: ");
int n = in.nextInt();
System.out.println("Pythagorean Triplets upto " + n + " are:\n");
for (a = 1; a <= n; a++) {
for (b = a; b <= n; b++) {
for (c = 1; c <= n; c++) {
if (a * a + b * b == c * c) {
System.out.print(a + ", " + b + ", " + c);
System.out.println();
}
else
continue;
}
}
}
}}