Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2501254
  • 博文数量: 308
  • 博客积分: 5547
  • 博客等级: 大校
  • 技术积分: 3782
  • 用 户 组: 普通用户
  • 注册时间: 2009-11-24 09:47
个人简介

hello world.

文章分类

全部博文(308)

分类: C/C++

2011-05-01 16:48:37

    四方定理是数论中的重要定理,它可以叙述为:所有自然数最多只要4个数的平方和就可以表示,编写一个程序验证四方定理。
    要验证四方定理,因此我们可以使用穷举法,对一个数,先用1一个数的平方和,2个数平方和,3个平方数的平方和,4个数的平方和进行验证。如果成功返回1,失败返回0;当穷举完所有情况后,就可以验证四方定理了,代码如下:
  1. #include <stdio.h>
  2. #include <math.h>

  3. int mode_1(int n)
  4. {
  5.   if((int)sqrt(n) * (int)sqrt(n) == n){
  6.     printf("%d * %d = %d \n",(int)sqrt(n),(int)sqrt(n),n);
  7.     return 1;
  8.   }
  9.   else{
  10.     return 0;
  11.   }
  12. }

  13. int mode_2(int n)
  14. {
  15.   int x,y;
  16.   for(x=1; x<sqrt(n); x++)
  17.     for(y=x; y<sqrt(n); y++){
  18.       if(x*+ y*== n){
  19.         printf("%d^2 + %d^2 = %d\n",x,y,n);
  20.         return 1;
  21.       }
  22.     }
  23.   return 0;
  24. }

  25. int mode_3(int n)
  26. {
  27.   int x,y,z;
  28.   for(x=1; x<sqrt(n); x++)
  29.     for(y=x; y<sqrt(n); y++)
  30.       for(z=y; z<sqrt(n); z++){
  31.         if(x*+ y*+ z*== n){
  32.           printf("%d^2 + %d^2 + %d^2 = %d\n",x,y,z,n);
  33.           return 1;
  34.     }
  35.       }

  36.   return 0;
  37. }

  38. int mode_4(int n)
  39. {
  40.   int x,y,z,t;
  41.   for(x=1; x<sqrt(n); x++)
  42.     for(y=x; y<sqrt(n); y++)
  43.       for(z=y; z<sqrt(n); z++)
  44.         for(t=z; t<sqrt(n); t++)
  45.           if(x*+ y*+ z*+ t*== n){
  46.             printf("%d^2 + %d^2 + %d^2 + %d^2 = %d\n",x,y,z,t,n);
  47.             return 1;
  48.      }
  49.  
  50.   return 0;
  51. }

  52. void proveFourSquares(int n)
  53. {
  54.   if(mode_1(n))
  55.     printf("it has verified four squares\n");
  56.   else if(mode_2(n))
  57.     printf("it has verified four squares\n");
  58.   else if(mode_3(n))
  59.     printf("it has verified four squares\n");
  60.   else if(mode_4(n))
  61.     printf("it has verified four squares\n");
  62. }

  63. int main(int argc, char *argv[])
  64. {
  65.   int n;
  66.   printf("please input a natural number\n");
  67.   scanf("%d",&n);
  68.   printf("--------------------------\n");
  69.   proveFourSquares(n);

  70.   return 0;
  71. }
执行结果如下:
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
阅读(2164) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~