两个数的公约数,指的是能同时被这两个数整除的整除。比如:3和6的的公约数是1,3,最大公约数便是3。C语言来求最大公约数右好多种方法,我就用了相减法和辗转相除法两种
相减法:
例子:
a = 7, b = 3
a = 7-3 = 4, b = 3
a = 4-3 = 1, b = 3
a = 1, b = 3-1 = 2
a = 1, b = 2-1 = 1
代码:
#include <stdio.h>
int main()
{
int a = 0;
int b = 0;
printf("请输入两个数:");
scanf("%d%d", &a, &b);
while (a != b)
{
if (a > b)
a = a - b;
else
b = b - a;
/*
a = a > b ? (a = a - b) : a;
b = b > a ? (b = b - a) : b;
*/
}
printf("公约数为:%d\n", a);
return 0;
}
结果事例:
辗转相除法:
例子:
a = 3, b = 6, c = 3%6 = 3
a = 6, b = 3, c = 6%3 = 0
代码:
#include <stdio.h>
int main()
{
int a = 0;
int b = 0;
int c = 0;
printf("请输入两个数:");
scanf("%d%d", &a, &b);
c = a%b;
while (c)
{
a = b;
b = c;
c = a%b;
}
printf("公约数为:%d\n", b);
return 0;
}
结果事例: