算法篇----求两数的最大公约数和最小公倍数

https://blog.csdn.net/qq_31828515/article/details/51812154

https://blog.csdn.net/troubleshooter/article/details/25394959

一、最大公约数与最小公倍数

最大公约数,属于数论所探究的内容。

最大公约数可以通过下面的三种方法求出来。

最小公倍数呢,它与最大公约数的乘机为所求数之积。

 

比如求  x,y的最大公约数和最小公倍数

记住这个公式: x*y=最小公倍数*最大公约数

这样以来求出最大公约数后就可以求出最小公倍数

二、求最大公约数的三种方法

①辗转相除法

算法流程图

代码块:

[cpp]  view plain  copy
  1. int measure(int x, int y)  
  2. {     
  3.     int z = y;  
  4.     while(x%y!=0)  
  5.     {  
  6.         z = x%y;  
  7.         x = y;  
  8.         y = z;    
  9.     }  
  10.     return z;  
  11. }  


 

运行结果:

②辗转相减法

扫描二维码关注公众号,回复: 1889385 查看本文章

代码块:

[cpp]  view plain  copy
  1. int measure(int a,int b)  
  2. {         
  3.     while(a != b)  
  4.     {  
  5.         if(a>b)  
  6.         {  
  7.             a = a - b;  
  8.         }  
  9.         else   
  10.         {  
  11.             b = b - a;  
  12.         }  
  13.     }  
  14.     return a;  
  15. }  


运行结果:

③穷举法

流程图:

代码块:

[cpp]  view plain  copy
  1. int measure(int x,int y)  
  2. {  
  3.     int temp = 0;  
  4.     for(temp = x ; ; temp-- )  
  5.     {  
  6.         if(x%temp == 0 && y%temp==0)   
  7.             break;   
  8.     }  
  9.     return temp;  
  10. }  

代码实现

  1. //****************************************************************************************************  
  2. //  求两个自然数的最小公倍数 - C++ -
  3. //  最小公倍数 = 两数的乘积 / 最大公约数  
  4. //****************************************************************************************************  
  5.   
  6. #include <iostream>  
  7. #include <cassert>  
  8. #include <stack>  
  9. #include <math.h>  
  10.   
  11. using namespace std ;  
  12.   
  13. int GreatestCommonDivisor(int a, int b)  
  14. {  
  15.     int temp;  
  16.   
  17.     if(a < b)  
  18.     {  
  19.         // 交换两个数,使大数放在a的位置上。  
  20.         temp = a;  
  21.         a = b;  
  22.         b = temp;  
  23.     }  
  24.   
  25.     while(b != 0)  
  26.     {  
  27.         // 利用辗转相除法,直到b为0为止。  
  28.         temp = a % b;  
  29.         a = b;  
  30.         b = temp;  
  31.     }  
  32.   
  33.     return a;  
  34. }  
  35.   
  36. int LeastCommonMultiple(int a, int b)  
  37. {  
  38.     int temp = a * b / GreatestCommonDivisor(a, b);  
  39.     return temp;  
  40. }  
  41.   
  42. int main()  
  43. {  
  44.     cout << LeastCommonMultiple(318, 87632) << endl;  
  45.     return 0;  
  46. }  

猜你喜欢

转载自blog.csdn.net/qq_34793133/article/details/80305401