12,943,913 members (58,738 online)

#### Stats

28.9K views
23 bookmarked
Posted 24 Aug 2007

# Template Meta Programming and Number Theory: Part 2

, 24 Aug 2007 CPOL
Using C++ language constructs to introduce abstraction layers
 ```// NLUMP.h // Author: Zeeshan Amjad // // Number Theory Library Using Meta Programming // #ifndef _NLUMP_H #define _NLUMP_H #include "functional.h" #include "Control.h" // check divisibility template struct Divisible { enum { value = v % u == 0 ? 1 : 0 }; }; // check divide by zero condition template struct Divisible { enum { value = -1 }; }; // check if one number is divide by other template struct DivisibleDigit { enum { value = v % u == 0 ? u : 0 }; }; // check divide by zero condition template struct DivisibleDigit { enum { value = -1 }; }; // check number is even or not template struct IsEven { enum { value = Divisible::value }; }; // check number is odd or not template struct IsOdd { enum { value = Divisible::value == 0 ? 1 : 0 }; }; // calculate gcd template struct gcd { enum { value = gcd::value }; }; template struct gcd { enum { value = u }; }; template <> struct gcd<0, 0> { enum { value = -1 }; }; // calculate lcm template struct lcm { enum { value = u * v / gcd::value }; }; // check if numbers are coprime (relative prime) or not template struct CoPrime { enum { value = gcd::value == 1 ? 1 : 0 }; }; // to calculate the power template struct Power { enum { value = a*Power::value }; }; template struct Power { enum { value = 1 }; }; // number of divisor of any positive digit template struct NoOfDivisor { enum { value = ForLoop<1, n, 1, Add, Add, Divisible>::value }; }; // check the given number is prime or not template class IsPrime { public: enum { value = NoOfDivisor::value == 2 ? 1 : 0 }; }; // sum of divisor of any positive digit template struct SumOfDivisor { enum { value = ForLoop<1, n, 1, Add, Add, DivisibleDigit>::value }; }; // check no is perfect or not template struct IsPerfect { enum { value = SumOfDivisor::value - n == n ? 1 : 0 }; }; // totient function template struct Totient { enum { value = ForLoop<1, n, 1, Add, Add, CoPrime>::value }; }; template struct TotientVal { enum { value = Totient::value }; }; // totient summatory function template struct TotientSummatory { enum { value = ForLoop<1, n, 1, Add, Add, TotientVal>::value }; }; // divisor function template struct Divisor { template struct DivisorPow { enum { value = Divisible::value == 1 ? Power::value : 0 }; }; enum { value = ForLoop<1, n, 1, Add, Add, DivisorPow>::value }; }; #endif ```

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.