【C语言做题系列】Perfect Cubes

For hundreds of years Fermat’s Last Theorem, which stated simply that for n > 2 there exist no integers a, b, c > 1 such that a^n = b^n + c^n, has remained elusively unproven. (A recent proof is believed to be correct, though it is still undergoing scrutiny.) It is possible, however, to find integers greater than 1 that satisfy the ``perfect cube’’ equation a^3 = b^3 + c^3 + d^3 (e.g. a quick calculation will show that the equation 12^3 = 6^3 + 8^3 + 10^3 is indeed true). This problem requires that you write a program to find all sets of numbers {a, b, c, d} which satisfy this equation for a <= 200.
Output
The output should be listed as shown below, one perfect cube per line, in non-decreasing order of a (i.e. the lines should be sorted by their a values). The values of b, c, and d should also be listed in non-decreasing order on the line itself. There do exist several values of a which can be produced from multiple distinct sets of b, c, and d triples. In these cases, the triples with the smaller b values should be listed first.

The first part of the output is shown here:

Cube = 6, Triple = (3,4,5)
Cube = 12, Triple = (6,8,10)
Cube = 18, Triple = (2,12,16)
Cube = 18, Triple = (9,12,15)
Cube = 19, Triple = (3,10,18)
Cube = 20, Triple = (7,14,17)
Cube = 24, Triple = (12,16,20)

Note: The programmer will need to be concerned with an efficient implementation. The official time limit for this problem is 2 minutes, and it is indeed possible to write a solution to this problem which executes in under 2 minutes on a 33 MHz 80386 machine. Due to the distributed nature of the contest in this region, judges have been instructed to make the official time limit at their site the greater of 2 minutes or twice the time taken by the judge’s solution on the machine being used to judge this problem.
题意:
有四个整数a,b,c,d, 找出整数a在(a<=200)范围内,符合(a^3 = b^3 + c^3 + d^3)的所有集合,并按样例输出。
注意:
每行一个完美的立方体,按a的非递减顺序排列(即每行应该按照它们的a值排序)。存在一些a值,它们可以由b、c和d三元组的多个不同集合产生,b、c和d的值也应该在直线上以非递减的顺序列出,即先列出b值较小的三元组。(遵照样例输出)
其次,a,b,c,d,在循环取初值的时候需要注意。
算法思想:
把a,b,c,d的数都遍历一遍,找出符合条件的数并输出即可。
上代码:

#include <stdio.h>
#include <algorithm>
using namespace std;
const int maxn=1e5+5;
int a[maxn];

int main()
{
    int a,b,c,d;
    for(a=6;a<=200;a++)              //此处a=6
    {
        for(b=2;b<a;b++)             //此处b=2
            for(c=b;c<a;c++)         //因为应该直线递增输入,所以,c的初值就从b开始
                for(d=c;d<a;d++)      //c的初值同上
                if(a*a*a==b*b*b+c*c*c+d*d*d)
                printf("Cube = %d, Triple = (%d,%d,%d)\n", a, b, c, d);
    }
    return 0;
}

注:可能是审题网站的问题,当我的a,b,取其他的初值的时候就wrong了,可能是为了减少时间复杂度吧。
心得:
任何一个关于遍历的题目尤其需要注意初值和末值的取定,否则就会出错。

发布了16 篇原创文章 · 获赞 0 · 访问量 451

猜你喜欢

转载自blog.csdn.net/qq_45627679/article/details/104261213