辗转相除法

来源:互联网 发布:手机淘宝试用在哪里 编辑:程序博客网 时间:2024/05/19 13:09

「辗转相除法」又叫做「欧几里得算法」,是公元前 300 年左右的希腊数学家欧几里得在他的著作《几何原本》提出的.利用这个方法,可以较快地求出两个自然数的最大公因数,即 HCF 或叫做 gcd.所谓最大公因数,是指几个数的共有的因数之中最大的一个,例如 8 和 12 的最大公因数是 4,记作 gcd(8,12)=4.





#include <stdio.h> int main(){int a;int b;int num1;int num2;int temp;printf("Input a & b:");scanf("%d%d",&num1,num2);if(num1 > num2){temp = num1;num1 = num2;num2 = temp;}a = num1;b = num2;while(b != 0){temp = a % b;a = b;b = temp;} printf("The GCD of %d and %d is:%d\n",num1,num2,a);printf("The LCM of them is :%d\n",num1*num2/a);return 0;}
运行结果:
Input a & b:20 5

The GCD of 20 and 5 is:5The LCM of them is :20

0 0
原创粉丝点击