Few clever algorithms for fast power x^N

This commit is contained in:
Guilhem Lavaux 2012-05-21 19:11:14 -04:00
parent 604b19ce74
commit 530c6f4fcd
2 changed files with 79 additions and 0 deletions

20
sample/testAlgo.cpp Normal file
View File

@ -0,0 +1,20 @@
#include <iostream>
#include <stdio.h>
#include "algo.hpp"
using namespace CosmoTool;
using namespace std;
int main(int argc, char **argv)
{
cout << square(2) << endl;
cout << cube(2) << endl;
cout << square(2.1f) << endl;
cout << cube(2.1f) << endl;
cout << spower<2>(2.1f) << endl;
cout << spower<3>(2.1f) << endl;
cout << spower<4>(2.1f) << endl;
cout << spower<5>(2.1f) << endl;
return 0;
}

59
src/algo.hpp Normal file
View File

@ -0,0 +1,59 @@
#ifndef __COSMOTOOL_ALGO_HPP
#define __COSMOTOOL_ALGO_HPP
#include "config.hpp"
namespace CosmoTool
{
template<typename T>
T cube(T a)
{
return a*a*a;
}
template<typename T>
T square(T a)
{
return a*a;
}
template<int N>
class SPowerBase
{
public:
template<typename T>
static T spower(T a)
{
if ((N%2)==0)
{
T b = SPowerBase<N/2>::spower(a);
return b*b;
}
T b = SPowerBase<(N-1)/2>::spower(a);
return a*b*b;
}
};
template<>
class SPowerBase<0>
{
public:
template<typename T>
static T spower(T a)
{
return T(1);
}
};
template<int N, typename T>
T spower(T a)
{
return SPowerBase<N>::spower(a);
}
};
#endif