递归实现求两数最大公约数

来源:互联网 发布:windows安全配置手册 编辑:程序博客网 时间:2024/06/06 20:36
// 递归实现求最大公约数.cpp : 定义控制台应用程序的入口点。
//


#include "stdafx.h"
#include <iostream>
using namespace std ;
int publicsum(int m,int t)
{
if (m==0||t==0)
{
cout<<"输入的数有错"<<endl;
return 0;
}
else if (m==1||t==1)
{
return 1;
}
if(m<t)
{
int i=t;
t=m;
m=i;
}
if(m%t==0)//如果除于t等于0,就是说t就是为最大公约数,返回一个商T
{
return t;
}
else//否则
{
return publicsum(t,m%t);//以除数作为被除数,余数作为除数,递归调用自己,直
//到上面那个if成立,结束递归
}
    return t;
}
int _tmain(int argc, _TCHAR* argv[])
{
int m,t;
cout<<"请输入要求最大公约数的两个整数"<<endl;
cin>>m>>t;
int o=publicsum(m,t);
cout<<"所求最大公约数是:"<<o;
return 0;

}



0 0
原创粉丝点击