两个数字的GCD是将两个数字相除的最大数字。查找GCD的一种简单方法是分解两个数并乘以公因数。
// C program to demonstrate Basic Euclidean Algorithm
#include
// Function to return gcd of a and b
int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
// Driver program to test above function
int main()
{
int a = 10, b = 15;
printf("GCD(%d, %d) = %d\n", a, b, gcd(a, b));
a = 35, b = 10;
printf("GCD(%d, %d) = %d\n", a, b, gcd(a, b));
a = 31, b = 2;
printf("GCD(%d, %d) = %d\n", a, b, gcd(a, b));
return 0;
}
输出:
GCD(10, 15) = 5
GCD(35, 10) = 5
GCD(31, 2) = 1
时间复杂度: O(Log min(a,b))
请参阅有关基本和扩展欧几里德算法的完整文章,以了解更多详细信息!
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。