/*=====================================完美立方总时间限制: 1000ms 内存限制: 65536kB描述a的立方 = b的立方 + c的立方 + d的立方为完美立方等式。例如12的立方 = 6的立方 + 8的立方 + 10的立方 。编写一个程序,对任给的正整数N (N≤100),寻找所有的四元组(a, b, c, d),使得a的立方 = b的立方 + c的立方 + d的立方,其中a,b,c,d 大于 1, 小于等于N。输入正整数N (N≤100)输出每行输出一个完美立方,按照a的值,从小到大依次输出。当两个完美立方等式中a的值相同,则依次按照b、c、d进行非降升序排列输出,即b值小的先输出、然后c值小的先输出、然后d值小的先输出。样例输入24样例输出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) 解析:4层for循环可以做,枚举法 a的循环范围从2到Nb的循环范围也是从2到Nc的循环范围从b开始到Nd的循环范围从c开始到N输出结果要注意严格按照输入输出案例里面的空格设置方式来设置。 ======================================*/
1 #include2 int main() 3 { 4 int a,b,c,d,N; 5 int a3,b3,c3,d3; 6 scanf("%d",&N); 7 for(a=2;a<=N;a++) 8 { 9 a3=a*a*a;10 for(b=2;b<=N;b++)11 {12 b3=b*b*b;13 if(a3
看看下面的三重for循环的代码:
1 #include2 #include 3 int main(int argc, char *argv[]) 4 { 5 int a,b,c,d,n,t; 6 scanf("%d",&n); 7 for(a=2;a<=n;a++) 8 { 9 for(b=2;b<=n;b++)10 {11 for(c=b;c<=n;c++)12 {13 t=a*a*a-b*b*b-c*c*c;14 d=(int)(pow(t,1.0/3)+0.5);15 if(d*d*d==t&&d>c&&d<=n)16 {17 printf("Cube = %d, Triple = (%d,%d,%d)\n",a,b,c,d);18 }19 }20 }21 }22 return 0;23 }
注意题目要求的输出顺序比较特殊,所以下面这段代码是错误的:
1 #include2 #include 3 int main(int argc, char *argv[]) 4 { 5 int a,b,c,d,n,a3; 6 scanf("%d",&n); 7 for(b=2;b<=n;b++) 8 { 9 for(c=b;c<=n;c++)10 {11 for(d=c;d<=n;d++)12 {13 a3=b*b*b+c*c*c+d*d*d;14 a=pow(a3,1.0/3)+0.5;15 if(a*a*a==a3&&a>1&&a<=n)16 {17 printf("Cube = %d, Triple = (%d,%d,%d)\n",a,b,c,d);18 }19 }20 }21 }22 return 0;23 }
运行结果:
24Cube = 18, Triple = (2,12,16)Cube = 6, Triple = (3,4,5)Cube = 19, Triple = (3,10,18)Cube = 12, Triple = (6,8,10)Cube = 20, Triple = (7,14,17)Cube = 18, Triple = (9,12,15)Cube = 24, Triple = (12,16,20)请按任意键继续. . .