您的位置:首页 > 其它

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

2017-03-22 17:15 183 查看
#include<stdio.h>

#include<iostream>

using namespace std;

void way1()   //穷举法

{
cout<<"请输入两个整数:";
int a,b;
cin>>a>>b;   //从键盘输入两个数
int n=a;
if (n>b)
n=b;   //取两个数中的较小数

    for(int i=n;i>=1;i--)
{
if (a%i==0&&b%i==0)
{
cout<<"最大公约数:"<<i<<endl;
break;
}
}

}

void way2()   //辗转相除法

{
int a,b,temp,x;
cout<<"请输入两个整数:";

    cin>>a>>b;  
if(a>b)   //选出较小的数
{
temp=b;
b=a;
a=temp;
}
while(b%a!=0)  //算出余数
{
x=b%a;
b=a;
a=x;
}
cout<<"最大公约数:"<<a<<endl;

}

void way3()  //辗转相减法

{  

    int a,b; 

    cout<<"请输入两个整数:";

    cin>>a>>b;   //从键盘输入两个数

    while(1)  

    {  

        if(a>b)  

        {  

            a = a-b;    //将两个数的差值赋给最大的一个  

        }  

        else if(a<b)  

        {  

            b = b-a;  

        }  

        else   

        {  

            cout<<"最大公约数:"<<b<<endl;

            break;    //跳出整个循环  

        }  

    }  

}

void main()

{
cout<<"求最大公约数的方法:"<<endl;
cout<<"1.穷举法"<<endl;
cout<<"2.辗转相除法"<<endl;
cout<<"3.辗转相减法"<<endl;
cout<<"4.退出系统"<<endl;
while(1)
{
cout<<"请选择方法编号:";
int n;
cin>>n;
switch(n)
{
case 1:way1();break;
case 2:way2();break;
case 3:way3();break;
case 4:return;
default:cout<<"输入错误,请重新选择"<<endl;
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: