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

【求最大公约数-辗转相除法】输入任一的自然数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;
}
时间限制 1 秒
内存限制 128 MB
讨论 统计
上一题 下一题