最大公约数的欧几里得算法
1 // C program to demonstrate Basic Euclidean Algorithm 2 #include <stdio.h> 3 4 // Function to return gcd of a and b 5 int gcd(int a, int b) 6 { 7 if (a == 0) 8 return b; 9 return gcd(b%a, a); 10 } 11 12 // Driver program to test above function 13 int main() 14 { 15 int a = 10, b = 15; 16 printf("GCD(%d, %d) = %dn", a, b, gcd(a, b)); 17 a = 35, b = 10; 18 printf("GCD(%d, %d) = %dn", a, b, gcd(a, b)); 19 a = 31, b = 2; 20 printf("GCD(%d, %d) = %dn", a, b, gcd(a, b)); 21 return 0; 22 }
运行结果
$gcc -o main *.c
$main
GCD(10, 15) = 5 GCD(35, 10) = 5 GCD(31, 2) = 1