1114 - C语言2.11
时间限制 : 1 秒
内存限制 : 32 MB
读入两个正整数m和n,计算m和n的最大公约数。
题目输入
两个空格隔开的正整数m和n。
题目输出
m和n的最大公约数。注意行尾输出换行。
输入/输出样例
输入格式
35 14
输出格式
7
C语言解答
#include<stdio.h> int main(){ int m,n,temp; scanf("%d %d",&m,&n); while(m%n!=0){ temp=n; n=m%n; m=temp;} printf("%d\n",n); return 0; }
C++解答
#include <stdio.h> int main() { int m, n, t; scanf("%d %d", &m, &n); /* 比较m和n的大小,通过交换保证m <= n */ if (m > n) { t = m; m = n; n = t; } /* 进行欧几里得辗转相除法求出最大公约数,并保存在n中 */ while (m != 0) { t = m; m = n % m; n = t; } printf("%d\n", n); return 0; }
Java解答
import java.util.*; public class Main { public static void main(String args[]) { Scanner cin = new Scanner(System.in); int m,n; int temp; m=cin.nextInt(); n=cin.nextInt(); if(m<n){ temp=m; m=n; n=temp; } while(n!=0){ temp=m%n; m=n; n=temp; } System.out.println(m); } }
Python解答
def gcd(a, b): while b: a, b = b, a%b return a a,b = raw_input().split() print gcd(int(a),int(b))