辗转相除法

来源:互联网 发布:玛格丽塔披萨 知乎 编辑:程序博客网 时间:2024/05/19 14:51

「辗转相除法」又叫做「欧几里得算法」,是公元前 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.       
0 0
原创粉丝点击