|
// 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 <int u, int v>
struct Divisible
{
enum { value = v % u == 0 ? 1 : 0 };
};
// check divide by zero condition
template <int u>
struct Divisible<u, 0>
{
enum { value = -1 };
};
// check if one number is divide by other
template <int u, int v>
struct DivisibleDigit
{
enum { value = v % u == 0 ? u : 0 };
};
// check divide by zero condition
template <int u>
struct DivisibleDigit<u, 0>
{
enum { value = -1 };
};
// check number is even or not
template <int u>
struct IsEven
{
enum { value = Divisible<u, 2>::value };
};
// check number is odd or not
template <int u>
struct IsOdd
{
enum { value = Divisible<u, 2>::value == 0 ? 1 : 0 };
};
// calculate gcd
template <int u, int v>
struct gcd
{
enum { value = gcd<v, u % v>::value };
};
template <int u>
struct gcd<u, 0>
{
enum { value = u };
};
template <>
struct gcd<0, 0>
{
enum { value = -1 };
};
// calculate lcm
template <int u, int v>
struct lcm
{
enum { value = u * v / gcd<u, v>::value };
};
// check if numbers are coprime (relative prime) or not
template <int u, int v>
struct CoPrime
{
enum { value = gcd<u, v>::value == 1 ? 1 : 0 };
};
// to calculate the power
template <int a, int b>
struct Power
{
enum { value = a*Power<a, b-1>::value };
};
template <int a>
struct Power<a, 0>
{
enum { value = 1 };
};
// number of divisor of any positive digit
template <int n>
struct NoOfDivisor
{
enum { value = ForLoop<1, n, 1, Add, Add, Divisible>::value };
};
// check the given number is prime or not
template <int n>
class IsPrime
{
public:
enum { value = NoOfDivisor<n>::value == 2 ? 1 : 0 };
};
// sum of divisor of any positive digit
template <int n>
struct SumOfDivisor
{
enum { value = ForLoop<1, n, 1, Add, Add, DivisibleDigit>::value };
};
// check no is perfect or not
template <int n>
struct IsPerfect
{
enum { value = SumOfDivisor<n>::value - n == n ? 1 : 0 };
};
// totient function
template <int n>
struct Totient
{
enum { value = ForLoop<1, n, 1, Add, Add, CoPrime>::value };
};
template <int n, int v = 0>
struct TotientVal
{
enum { value = Totient<n>::value };
};
// totient summatory function
template <int n>
struct TotientSummatory
{
enum { value = ForLoop<1, n, 1, Add, Add, TotientVal>::value };
};
// divisor function
template <int n, int x>
struct Divisor
{
template <int Start, int End>
struct DivisorPow
{
enum { value = Divisible<Start, End>::value == 1 ? Power<Start, x>::value : 0 };
};
enum { value = ForLoop<1, n, 1, Add, Add, DivisorPow>::value };
};
#endif
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
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.