C语言实现辗转相除法求最大公约数
以下是使用辗转相除法求两个正整数m和n的最大公约数的C语言代码:
#include <stdio.h>
int gcd(int m, int n) {
int remainder;
while (n != 0) {
remainder = m % n;
m = n;
n = remainder;
}
return m;
}
int main() {
int m, n;
printf("Enter two positive integers: ");
scanf("%d %d", &m, &n);
int result = gcd(m, n);
printf("The greatest common divisor of %d and %d is %d\n", m, n, result);
return 0;
}
这段代码定义了一个gcd函数,接受两个正整数m和n作为参数,使用辗转相除法求它们的最大公约数,并返回最大公约数的值。
在main函数中,先提示用户输入两个正整数,然后调用gcd函数求最大公约数,并将结果打印出来。
原文地址: https://www.cveoy.top/t/topic/dSXd 著作权归作者所有。请勿转载和采集!