任何一种编程语言,能做的事情都是对数据的存取、运算、测试,分支和循环(迭代)。
利用Eculid方法来求最大公约数和最小公倍数
#include "stdafx.h"
#include <iostream>//程序描述:用Euclid法来计算两个数的最大公约数
#define MODE1 0
#define MODE2 1
#define MODE MODE2
using namespace std;
int gcd(int a, int b);
int lcm(int a, int b);
int main()
{
int a, b;
cout << "please input a, b" << endl;
cin >> a;
cin >> b;
cout << "the geratest common factor is : " << gcd(a, b) <<endl;
cout << "the lowest common multiple is : " << lcm(a,b) << endl;
return 0;
}
int gcd(int a,int b)
{
#if MODE ==MODE1
int m, n,temp;
if (a >= b)
{
m = a;
n = b;
}
else
{
m = b;
n = a;
}
if (m%n == 0)
{
return n;
}
else
{
temp = n;
n = m%n;
m = temp;
return gcd(m, n);
}
#endif
#if MODE == MODE2
int temp;
if(a<b)
{
temp = a;
a = b;
b = temp;
}
while (b != 0)
{
temp = a%b;
a = b;
b = temp;
}
return (a);
#endif
}
int lcm(int a, int b)
{
int temp;
if (a < b)
{
temp = a;
a = b;
b = temp;
}
return ((a*b) / gcd(a, b));
}