Find Pythagorean triplet for which a + b + c = 1000

后端 未结 16 2639
离开以前
离开以前 2020-12-24 13:13

A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2

For example, 32 + 4

16条回答
  •  庸人自扰
    2020-12-24 14:01

    #include 
    #include 
    
    int main()
    {
        const int sum = 1000;
        int a;
        for (a = 1; a <= sum/3; a++)
        {
            int b;
            for (b = a + 1; b <= sum/2; b++)
            {
                int c = sum - a - b;
                if ( a*a + b*b == c*c )
                   printf("a=%d, b=%d, c=%d\n",a,b,c);
            }
        }
        return 0;
    }
    

    explanation:

    • b = a;
      if a, b (a <= b) and c are the Pythagorean triplet,
      then b, a (b >= a) and c - also the solution, so we can search only one case
    • c = 1000 - a - b; It's one of the conditions of the problem (we don't need to scan all possible 'c': just calculate it)

提交回复
热议问题