Last active
December 10, 2016 18:40
-
-
Save C0nsultant/83f4652cee41b741e8c1077720b6fbd5 to your computer and use it in GitHub Desktop.
C++ header to calculate pow(B,E) at compiletime in O(log(E))
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#if __cplusplus > 199711L | |
#include <cstdint> | |
constexpr uint64_t pow_impl(uint64_t B, uint64_t E, uint64_t res = 1) | |
{ | |
return E < 1 ? res : pow_impl(B*B, E/2, E%2 ? B*res : res); | |
} | |
template<uint64_t B, uint64_t E> | |
struct Pow | |
{ | |
static constexpr uint64_t value = pow_impl(B, E); | |
}; | |
#else | |
#define SQ(a) ((a)*(a)) | |
#include <stdint.h> | |
template<uint64_t B, uint64_t E> | |
struct Pow; | |
template<uint64_t B> | |
struct Pow<B, 0> | |
{ | |
static const uint64_t value = 1; | |
}; | |
template<uint64_t B, uint64_t E> | |
struct Pow | |
{ | |
private: | |
static const uint64_t v0 = Pow<B, E/2>::value; | |
public: | |
static const uint64_t value = SQ(v0)*(E%2 ? B : 1); | |
}; | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment