最大公约数
#include <bits/stdc++.h> //求两个整数的最大公因数 using namespace std; //m:元素1, n:元素2 int commonFactor1(int m, int n) { //使用循环实现 int mid = 520; while(mid) { mid = m % n; m = n; n = mid; } return m; } int commonFactor2(int m, int n) { //使用递归,注意判断条件 if(n == 0) { return m; } else { return commonFactor2(n, m%n); } } int commonFactor3(int m, int n) { //条件语句 + 递归 return ( n==0 ? m : commonFactor3(n, m%n) ); } void finishTask() { //任务函数 int num1, num2; while(true) { cout<< "请输入两个整数,以空格隔开, 输入0 0结束: "; cin>> num1>> num2; if(num2 == 0 || num2 == 0) { cout<< "0"<< endl; break; } cout<< commonFactor1(num1, num2)<< endl; cout<< commonFactor2(num1, num2)<< endl; cout<< commonFactor3(num1, num2)<< endl; } } int main() { finishTask(); return 0; }