c++ - How to calculate mersenne numbers in compile time -


note: q&a not mersenne twister, mersenne numbers.


i want compute, @ compile time, array of size n containing mersenne primes (2n − 1) n in [0, n - 1].

template <std::uint8_t n> static constexpr std::array<std::uint16_t, n> mersenne_numbers() {      // compute mersenne numbers n, n-1 ... 1 , return array     return { 1, 2, 3 }; };  int main() {     constexpr std::array<std::uint16_t, 5> arr = mersenne_numbers<5>(); } 

how can implement ?

so compute array of (2^n - 1) @ compile time, may do

template <std::size_t ... is> constexpr std::array<std::uint16_t, sizeof...(is)> mersenne_numbers(std::index_sequence<is...>) {     return {{ ((1u << is) - 1u)... }}; }  template <std::uint8_t n> constexpr std::array<std::uint16_t, n> mersenne_numbers() {     return mersenne_numbers(std::make_index_sequence<n>{}); } 

demo

implementation of index_sequence stuff can done in c++11, , found on so.

or in c++14

template <std::uint8_t n> constexpr std::array<std::uint16_t, n> mersenne_numbers() {     std::array<std::uint16_t, n> res{};     (uint = 0; != n; ++i)     {         res [i] = (1u << i) - 1;     }     return res; } 

demo


Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -