辗转相除法

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





[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #include <stdio.h>   
  2.   
  3. int main()  
  4. {  
  5.       
  6.     int a;  
  7.     int b;  
  8.     int num1;  
  9.     int num2;  
  10.     int temp;  
  11.       
  12.     printf("Input a & b:");  
  13.     scanf("%d%d",&num1,num2);  
  14.       
  15.     if(num1 > num2)  
  16.     {  
  17.         temp = num1;  
  18.         num1 = num2;  
  19.         num2 = temp;  
  20.           
  21.     }  
  22.     a = num1;  
  23.     b = num2;  
  24.       
  25.     while(b != 0)  
  26.     {  
  27.         temp = a % b;  
  28.         a = b;  
  29.         b = temp;  
  30.           
  31.     }   
  32.     printf("The GCD of %d and %d is:%d\n",num1,num2,a);  
  33.     printf("The LCM of them is :%d\n",num1*num2/a);  
  34.       
  35.     return 0;  
  36. }  
[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. 运行结果:  
[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. Input a & b:20 5  

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. The GCD of 20 and 5 is:5  
  2. The LCM of them is :20  
  3.       
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值