利用三种方法求两个整数的最大公约数

来源:互联网 发布:公司网络服务器搭建 编辑:程序博客网 时间:2024/05/22 06:12
/*
                      功能:运用多种方法求最大公约数
 作者:yy
 修改日期:2017-3-17 
*/

#include<iostream>
#include <cmath>

using namespace std;

class Cdivisor{


public:
int  rgcd(int x,int y);                  //递归法 
int  Cdivisibility(int x,int y);                //连续整除法 
int  Tdivisibility(int x,int y);                //辗转相除法

};


int k = 1;
int a,b ;
int main()
{   
   Cdivisor cd;
   cout<<"请输入两个整数(空格键间隔):"<<endl;
    cin>>a>>b;
   int num;

                cout<<"  ************************************************************************  "<<endl;

cout<<"  *                         求最大公约数                                 *"<<endl;
cout<<"  *                     1.递归法求最大公约数                             * "<<endl;
cout<<"  *                     2.辗转相除法求最大公约数                         *"<<endl;
cout<<"  *                     3.连续整数检测法求最大公约数                     *"<<endl;
cout<<"  *                     4.退出                                           *"<<endl;
cout<<"  ************************************************************************  "<<endl;
cout<<"  请选择一种方法求最大公约数:"<<endl;
cin>>num;


   switch(num)


        default:printf("请在1-4之间选择\n");
case 1:cd.rgcd(a,b);break;
case 2:cd.Cdivisibility(a,b);break;
case 3:cd.Tdivisibility(a,b);break;
case 4:k=0;break;

}

return 0;
while(k)
system("pause");

   
}
int Cdivisor::rgcd(int x,int y){
int z;
  if(x>=0&&y>=0)
   {   
       z = (y==0)?x:rgcd(y,x%y);
   
   
   }else
       {
          cout<< 0<<endl;
       }
                  cout<< z << endl;
    
                  system("pause");
}
int Cdivisor::Cdivisibility(int x,int y){
if(x>0&&y>0)
   {
       int t=(x<y)?x:y;
       while(t>0)
       {
           if(x%t==0)
           {
               if(y%t==0)
               {
                   
                   cout<<t<<endl;
                   system("pause");
                   break;
               }
           }
           t--;
       }
   }
    else
   {
       cout<<0<<endl;
   }
  
}
              
   int Cdivisor::Tdivisibility(int x,int y){
       int t,r;
       int Hcf; 
if(y>x)
 {
  t = x;
  x = y;
  y = t;
 }
while((r=x%y)!=0)
 {
  x = y;
  y = r;
 }
 Hcf = y;
 cout<<Hcf<<endl;
   }
0 0
原创粉丝点击