输入2个正整数A,B,求A与B的最大公约数。
Input
2个数A,B,中间用空格隔开。(1<= A,B <= 10^9)
Output
输出A与B的最大公约数。
Sample Input
30 105
Sample Output
Input
2个数A,B,中间用空格隔开。(1<= A,B <= 10^9)
Output
输出A与B的最大公约数。
Sample Input
30 105
Sample Output
15
注意:这个最大公约数范围就不需要最小公倍数的范围那么大了,可以用int。同样不要用最通俗的算法,不然超时,也要用欧几里得算法。
代码如下:(第一个我的,第二个舍友的)
法1.
1
2
3
4
5
6
7
8
9
10
11
12
13 | #include<stdio.h> //水题,用欧几里得算法 int main() {int a,b,i,j,r; scanf("%d%d",&a,&b); i=a<b?a:b; j=a>b?a:b; while(i!=0) {r=j%i; //大数变小数,小数变余数 j=i; i=r; } printf("%d",j); } |
法2.
1
2
3
4
5
6
7
8
9
10
11
12
13
14 | #include<stdio.h> // int main() { int GCD(int a,int b); int A,B; scanf("%d%d",&A,&B); printf("%d\n",GCD(A,B)); return 0; } int GCD(int a,int b) //大家最好记住这个模板,不知道算法的可以百度 { return b==0?a:GCD(b,a%b); } |