Dec 3, 2013

C++ template meta version of greatest common divisor and least common multiple.

I found these functions very useful often because it doesn't use any run-time computation cost. Calculations are done at compile time and intermediate values are not stored into the binary file.
It may increase compile time a lot if you try to get result with big numbers and only constant values can be used; no variables are allowed.

It is the functions:
template< int lhs, int rhs >
struct GreatestCommonDivisor
{
    enum { value = GreatestCommonDivisor< rhs, lhs % rhs >::value };
};

template< int lhs >
struct GreatestCommonDivisor< lhs, 0 >
{
    enum { value = lhs };
};

template< int lhs, int rhs >
struct LeastCommonMultiple
{
    enum { value = ( lhs * rhs ) / GreatestCommonDivisor< lhs, rhs >::value };
};

Here is how to use them:
int a = GreatestCommonDivisor< 24, 21 >::value;
int b = LeastCommonMultiple< 24, 21 >::value;
I hope this can help anybody who wants to improve the run-time performance.

No comments: