/************************************************************
* FileName: gcd-lcm.cpp
* Description: 求得两个数的最大公约数和最小公倍数
* Author: Cui Xiaofeng
* Date: 2008/3/15
* Version: 1.0
*************************************************************/
#include < cstdio >
#include < iostream >
#include < cassert >
using namespace std;
class GcdLcm
{
public:
GcdLcm(unsigned long a, unsigned long b);
unsigned long GcdNotRecur();
unsigned long GcdRecur();
unsigned long Lcm();
private:
unsigned long firstValue;
unsigned long secondValue;
unsigned long GcdRecurPrivate(unsigned long a , unsigned long b);
} ;
GcdLcm::GcdLcm(unsigned long a, unsigned long b):firstValue(a), secondValue(b)
{
}
unsigned long GcdLcm::GcdNotRecur()
{
unsigned long c;
/* copy the value, or they will be modified */
unsigned long a = firstValue;
unsigned long b = secondValue;
while ((a % b) != 0)
{
c = a % b;
a = b;
b = c;
}
return b;
}
unsigned long GcdLcm::GcdRecur()
{
return GcdRecurPrivate(firstValue, secondValue);
}
unsigned long GcdLcm::Lcm()
{
return (firstValue * secondValue) / GcdNotRecur();
}
/* private function invoked by GcdRecur */
unsigned long GcdLcm::GcdRecurPrivate(unsigned long a, unsigned long b)
{
if (0 == b)
{
return a;
}
else
{
return GcdRecurPrivate(b, a % b);
}
}
/* test function */
int main()
{
GcdLcm test(24, 56);
cout << test.GcdRecur() << endl;
cout << test.GcdNotRecur() << endl;
cout << test.Lcm() << endl;
return 0;
}
* FileName: gcd-lcm.cpp
* Description: 求得两个数的最大公约数和最小公倍数
* Author: Cui Xiaofeng
* Date: 2008/3/15
* Version: 1.0
*************************************************************/
#include < cstdio >
#include < iostream >
#include < cassert >
using namespace std;
class GcdLcm
{
public:
GcdLcm(unsigned long a, unsigned long b);
unsigned long GcdNotRecur();
unsigned long GcdRecur();
unsigned long Lcm();
private:
unsigned long firstValue;
unsigned long secondValue;
unsigned long GcdRecurPrivate(unsigned long a , unsigned long b);
} ;
GcdLcm::GcdLcm(unsigned long a, unsigned long b):firstValue(a), secondValue(b)
{
}
unsigned long GcdLcm::GcdNotRecur()
{
unsigned long c;
/* copy the value, or they will be modified */
unsigned long a = firstValue;
unsigned long b = secondValue;
while ((a % b) != 0)
{
c = a % b;
a = b;
b = c;
}
return b;
}
unsigned long GcdLcm::GcdRecur()
{
return GcdRecurPrivate(firstValue, secondValue);
}
unsigned long GcdLcm::Lcm()
{
return (firstValue * secondValue) / GcdNotRecur();
}
/* private function invoked by GcdRecur */
unsigned long GcdLcm::GcdRecurPrivate(unsigned long a, unsigned long b)
{
if (0 == b)
{
return a;
}
else
{
return GcdRecurPrivate(b, a % b);
}
}
/* test function */
int main()
{
GcdLcm test(24, 56);
cout << test.GcdRecur() << endl;
cout << test.GcdNotRecur() << endl;
cout << test.Lcm() << endl;
return 0;
}