码迷,mamicode.com
首页 > 编程语言 > 详细

最大公约数和最小公倍数算法实现

时间:2014-11-20 15:12:23      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   os   sp   for   

 

最大公约数

1. 用最基本的循环遍历的方法

2. 用辗转相除法

3. 用辗转相减法

 

See also:  http://baike.baidu.com/view/47637.htm

 

 1 #include<iostream>
 2 using namespace std;
 3 
 4 int CommonDivisor( int x, int y);
 5 int CommonMultiple(int x, int y);
 6 int CommonDivisor1( int x, int y);
 7 int CommonMultiple2(int x, int y);
 8 int CommonDivisor2(int x, int y);
 9 int getDif(int x, int y);
10 int main()
11 {
12     int a, b;
13     cout << "Please input two integer: ";
14     cin>>a >>b;
15 
16     cout<<CommonDivisor(a,b)<< endl;
17     cout<<CommonMultiple(a,b)<< endl;
18     cout<<"-----------------------------------"<< endl;
19     cout<<CommonDivisor1(a,b)<< endl;
20     cout<<CommonMultiple2(a,b)<< endl;
21 
22     cout<<"-----------------------------------"<< endl;
23     cout<<CommonDivisor2(a,b)<< endl;
24 
25     cout<<endl;
26 
27 }
28 
29 int CommonDivisor1( int x, int y)
30 {
31     //最大公约数一定在1和X和Y较小的值之间,因此从x和y之间较小的值开始循环遍历,找到最大的公约数
32     int start = x;
33     if(x > y)
34         start = y;
35     for (int i = start; i >=1; i--)
36     {
37         if(x % i ==0 && y % i == 0)
38             return i;
39     }
40     return 1;
41 }
42 
43 int CommonDivisor2(int x, int y)
44 {
45     //辗转相减法
46     if(x % 2 ==0 && y % 2 == 0)
47         return 2 * CommonDivisor2(x / 2, y / 2);
48     else
49     {
50         return getDif(x,y);
51     }
52 }
53 
54 int getDif(int x,int y)
55 {
56     int larger = x;
57     int smaller = y;
58     if(x < y)
59     {
60         larger = y;
61         smaller = x;
62     }
63     int dif =  larger - smaller;
64     if(dif == smaller )
65         return dif;
66     else
67         return getDif(smaller, dif);
68 }
69 
70 int CommonDivisor( int x, int y)
71 {
72     //辗转相除法
73     if(x== 0)
74         return y;
75     return CommonDivisor(y %x , x);
76 }
77 int CommonMultiple(int x, int y)
78 {
79     //最小公倍数是x和y的乘积 再除以x和y的最大公约数 所的出来的值
80     int cd = CommonDivisor(x,y);
81     return ((x * y ) / cd);
82 }
83 int CommonMultiple2(int x, int y)
84 {
85     //最小公倍数是的值一定在x和y中较大者和xy乘积之间,所以从小到大遍历找到这个数字
86     int start = x;
87     int end = x * y;
88     if(x < y)
89         start = y;
90     for(int i = y ; y <= end; i++)
91     {
92         if(i % x ==0 && i % y == 0)
93             return i;
94     }
95     return end;
96 }

 

最大公约数和最小公倍数算法实现

标签:style   blog   http   io   ar   color   os   sp   for   

原文地址:http://www.cnblogs.com/anthonyBlog/p/4110532.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!