3834 - 第六章:函数的使用《练习5:求最大公约数gcd》

通过次数

0

提交次数

0

时间限制 : 1 秒 内存限制 : 128 MB

【求最大公约数-辗转相除法】输入任一的自然数A, B, 求A , B的最大公约数。

输入:51 34
输出:17

include<cstdio>

using namespace std;

int gcd(int xx,int yy)
{
 if(xx==0) return yy;
 else return gcd(yy%xx,xx);
}
int main()
{
    int a,b,t;
    scanf("%d%d",&a,&b);
   
    printf("%d\n",gcd(a,b));
   
    return 0;
}

题目输入

题目输出

输入/输出样例

输入格式

34 51

输出格式

17

C语言解答

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int gcd(int x,int y)
{
    return y==0?x:gcd(y,x%y);
}
int main()
{
	int a,b;
    scanf("%d%d",&a,&b);
    printf("%d",gcd(a,b));
	return 0;
}

C++解答

#include<cstdio>
using namespace std;

int gcd(int xx,int yy)
{
 if(xx==0) return yy;
 else return gcd(yy%xx,xx);
}
int main()
{
    int a,b,t;
    scanf("%d%d",&a,&b);
    
    printf("%d\n",gcd(a,b));
    
    return 0;
}