游客 Signup | Login
中文 | En

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;
}

Input

Output

Examples

Input

34 51

Output

17

Solution 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;
}

Solution 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;
}
Time Limit 1 second
Memory Limit 128 MB
Discuss Stats
上一题 下一题