数学趣题——验证四方定理

1、题目

所有自然数最多只要4个数的平方和就可以表示

2、源码

   1: #include <stdio.h>
   2: #include <math.h>
   3:  
   4: int mode_1(int N)            /*判断自然数N是否可以表示成为N=a2的形式*/
   5: {
   6:     if((int)sqrt(N)*(int)sqrt(N)==N)
   7:     {
   8:       printf("%d*%d=%d\n",(int)sqrt(N),(int)sqrt(N),N);
   9:       return 1;
  10:     }
  11:     else return 0;
  12: }
  13:  
  14: int mode_2(int N)            /*判断自然数N是否可以表示成N=a2+b2的形式*/
  15: {
  16:     int x,y;
  17:     for(x=1;x<sqrt(N);x++)
  18:         for(y=x;y<sqrt(N);y++)
  19:         {
  20:             if(x*x+y*y == N)
  21:             {
  22:                 printf("%d^2+%d^2=%d\n",x,y,N);
  23:                 return 1;
  24:             }
  25:  
  26:         }
  27:     return 0;
  28: }
  29:  
  30: int mode_3(int N)            /*判断自然数N是否可以表示成N=a2+b2+c2的形式*/
  31: {
  32:     int x,y,z;
  33:     for(x=1;x<sqrt(N);x++)
  34:         for(y=x;y<sqrt(N);y++)
  35:             for(z=y;z<sqrt(N);z++)
  36:             {
  37:                 if(x*x+y*y+z*z == N)
  38:                  {
  39:                     printf("%d^2+%d^2+%d^2=%d\n",x,y,z,N);
  40:                      return 1;
  41:                  }
  42:             }
  43:     return 0;
  44: }
  45:  
  46: int mode_4(int N)            /*判断自然数N是否可以表示成N=a2+b2+c2+d2的形式*/
  47: {
  48:     int x,y,z,t;
  49:     for(x=1;x<sqrt(N);x++)
  50:         for(y=x;y<sqrt(N);y++)
  51:             for(z=y;z<sqrt(N);z++)
  52:                 for(t=z;t<sqrt(N);t++)
  53:                 {
  54:                      if(x*x+y*y+z*z+t*t == N)
  55:                      {
  56:                         printf("%d^2+%d^2+%d^2+%d^2=%d\n",x,y,z,t,N);
  57:                         return 1;
  58:                         }
  59:                 }
  60:     return 0;
  61: }
  62:  
  63: void proveFourSquares(int N)
  64: {
  65:     if(mode_1(N))
  66:     printf("It has verified Four Squares");
  67:     else if(mode_2(N))
  68:     printf("It has verified Four Squares");
  69:     else if(mode_3(N))
  70:     printf("It has verified Four Squares");
  71:     else if(mode_4(N))
  72:     printf("It has verified Four Squares");
  73: }
  74:  
  75: int main()
  76: {
  77:     int N;
  78:     printf("Please input a natural number\n");
  79:     scanf("%d",&N);
  80:     printf("-------- Step of Verification---------\n");
  81:     proveFourSquares(N);
  82:     return 0;
  83: }

你可能感兴趣的:(验证)