- You can see the answer to this question https://ask.csdn.net/questions/7763062
the answer wrong 90% < br / >
#include<iostream>
using namespace std;
int gcd(int a,int b)
{
int ans=1;
for(int i=2;i<=min(a,b);++i)
{
if(a%i==0 && b%i==0)
ans=i;
}
if(a==0 && b==0)
{
ans=0;
}
if(a==0 && b!=0)
{
ans=b;
}
if(a!=0 && b==0)
{
ans=a;
}
return ans;
}
int main()
{
int a,b;
cin>>a>>b;
cout<<gcd(a,b);
return 0;
}
Title Description
Definition :gcd(a,b)=b> 0? gcd(b,a%b):a
Enter two numbers A,B, find gcd(a,b)
Input
A
B
Output
gcd(A,B)
Sample input
0 0
Sample output
0
0 Answer
< div class = " aw-list-img " >
0 has no natural divisible with any number
So you can decide whether ans should be 0
We need to pay attention to some boundary cases in this problem. Here is an example of code that can pass:
#include
using namespace std;
int gcd(int a, int b) {
if (a == 0 && b == 0) {
return 0;
} else if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
int main() {
int a, b;
cin >> a >> b;
cout << gcd(abs(a), abs(b)); // 取绝对值
return 0;
}
Explain the code: first define a function for the greatest common divisor gcd, according to the definition can be implemented. Read two integers a and b into the main function and print their greatest common divisor. Note that the input number may be negative, so you need to take the absolute value. And notice some of the boundary cases in the problem, for example, when the input is 0, the output is 0.
这家伙很懒,什么都没留下...