四方定理是数论中的重要定理,它可以叙述为:所有自然数最多只要4个数的平方和就可以表示,编写一个程序验证四方定理。
要验证四方定理,因此我们可以使用穷举法,对一个数,先用1一个数的平方和,2个数平方和,3个平方数的平方和,4个数的平方和进行验证。如果成功返回1,失败返回0;当穷举完所有情况后,就可以验证四方定理了,代码如下:
- #include <stdio.h>
- #include <math.h>
- int mode_1(int n)
- {
- if((int)sqrt(n) * (int)sqrt(n) == n){
- printf("%d * %d = %d \n",(int)sqrt(n),(int)sqrt(n),n);
- return 1;
- }
- else{
- return 0;
- }
- }
- int mode_2(int n)
- {
- int x,y;
- for(x=1; x<sqrt(n); x++)
- for(y=x; y<sqrt(n); y++){
- if(x*x + y*y == n){
- printf("%d^2 + %d^2 = %d\n",x,y,n);
- return 1;
- }
- }
- return 0;
- }
- int mode_3(int n)
- {
- int x,y,z;
- for(x=1; x<sqrt(n); x++)
- for(y=x; y<sqrt(n); y++)
- for(z=y; z<sqrt(n); z++){
- if(x*x + y*y + z*z == n){
- printf("%d^2 + %d^2 + %d^2 = %d\n",x,y,z,n);
- return 1;
- }
- }
- return 0;
- }
- int mode_4(int n)
- {
- int x,y,z,t;
- for(x=1; x<sqrt(n); x++)
- for(y=x; y<sqrt(n); y++)
- for(z=y; z<sqrt(n); z++)
- for(t=z; t<sqrt(n); t++)
- if(x*x + y*y + z*z + t*t == n){
- printf("%d^2 + %d^2 + %d^2 + %d^2 = %d\n",x,y,z,t,n);
- return 1;
- }
-
- return 0;
- }
- void proveFourSquares(int n)
- {
- if(mode_1(n))
- printf("it has verified four squares\n");
- else if(mode_2(n))
- printf("it has verified four squares\n");
- else if(mode_3(n))
- printf("it has verified four squares\n");
- else if(mode_4(n))
- printf("it has verified four squares\n");
- }
- int main(int argc, char *argv[])
- {
- int n;
- printf("please input a natural number\n");
- scanf("%d",&n);
- printf("--------------------------\n");
- proveFourSquares(n);
- return 0;
- }
执行结果如下:
peng@ubuntu:~/src/test/c/suanfa/miaoqu$ gcc 6.5.c -lm
peng@ubuntu:~/src/test/c/suanfa/miaoqu$ ./a.out
please input a natural number
120
--------------------------
2^2 + 4^2 + 10^2 = 120
it has verified four squares
peng@ubuntu:~/src/test/c/suanfa/miaoqu$ ./a.out
please input a natural number
10
--------------------------
1^2 + 3^2 = 10
it has verified four squares
阅读(2283) | 评论(0) | 转发(0) |