本文介绍了查找a + b + c = 1000的毕达哥拉斯三联体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

毕达哥拉斯三联体是一组三个自然数,一个< b< c,为此,a + b = c

例如3 + 4 = 9 + 16 = 25 = 5 .

确切存在一个毕达哥拉斯三联体,其中a + b + c = 1000.找到产品abc.

来源: http://projecteuler.net /index.php?section=problems&id=9

我尝试过,但是不知道我的代码出了什么问题.这是我在C中的代码:

#include <math.h>
#include <stdio.h>
#include <conio.h>


void main()
{
    int a=0, b=0, c=0;
    int i;
    for (a = 0; a<=1000; a++)
    {
        for (b = 0; b<=1000; b++)
        {
            for (c = 0; c<=1000; c++)
            {
                if ((a^(2) + b^(2) == c^(2)) && ((a+b+c) ==1000)))
                    printf("a=%d, b=%d, c=%d",a,b,c);
            }
        }
    }
getch();
}
解决方案
#include <math.h>
#include <stdio.h>

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;
}

说明:

  • b = a;
    如果a,b(a< = b)和c是毕达哥拉斯三联体,
    然后b,a(b> = a)和c-也是解,所以我们只能搜索一种情况
  • c = 1000-a-b; 这是问题的条件之一(我们不需要扫描所有可能的"c":只需对其进行计算)

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

For example, 3 + 4 = 9 + 16 = 25 = 5.

There exists exactly one Pythagorean triplet for which a + b + c = 1000.Find the product abc.

Source: http://projecteuler.net/index.php?section=problems&id=9

I tried but didn't know where my code went wrong. Here's my code in C:

#include <math.h>
#include <stdio.h>
#include <conio.h>


void main()
{
    int a=0, b=0, c=0;
    int i;
    for (a = 0; a<=1000; a++)
    {
        for (b = 0; b<=1000; b++)
        {
            for (c = 0; c<=1000; c++)
            {
                if ((a^(2) + b^(2) == c^(2)) && ((a+b+c) ==1000)))
                    printf("a=%d, b=%d, c=%d",a,b,c);
            }
        }
    }
getch();
}
解决方案
#include <math.h>
#include <stdio.h>

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)

这篇关于查找a + b + c = 1000的毕达哥拉斯三联体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 08:50