特别的毕达哥拉斯三重奏是什么回答?

时间:2016-05-12 02:41:49

标签: java

public class Main {

   public static void main(String[] args) {

    // Special Pythagorean triplet Problem 9
    // There exists exactly one Pythagorean triplet for which a + b + c = 1000.
    // Find the product abc.
    // A Pythagorean triplet is a set of three natural numbers, a < b < c, for which
    int a = 1, b = a + 1, c = 0;

    while(true){
        ++a;
        ++b;
        c = 1000 - a - b;
        if(a * a + b * b == c * c && a < b && b < c)
            break;
    }
    System.out.println("Value of a is " + a);
    System.out.println("Value of b is " + b);
    System.out.println("Value of c is " + c);
    System.out.println((a + b + c));
    System.out.println((a * a) + (b * b));
    System.out.println((c * c));

   }

}

输出结果为:

Value of a is -1852266809
Value of b is -1852266808
Value of c is -590432679
1000
a^2 + b^2 is -420041039170392640
c^2 is -249648399

这个答案是否可以接受?

1 个答案:

答案 0 :(得分:1)

输出是不可接受的,因为实数的平方永远不会是负数,所以它们之和也不会是负数。发生溢出,这就是你得到错误结果的原因。

你做错了的是你只搜索b = a + 1。您应该在ab中检查整数1 <= a < b < 1000b < c的所有组合。