Guest User

Untitled

a guest
Jan 22nd, 2018
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.48 KB | None | 0 0
  1. template<unsigned p, unsigned d>
  2. struct DoIsPrime {
  3. static constexpr bool value = (p%d != 0) && DoIsPrime<p,d-1>::value;
  4. };
  5.  
  6. template<unsigned p>
  7. struct DoIsPrime<p, 2> {
  8. static constexpr bool value = (p % 2 != 0);
  9. };
  10.  
  11. template<unsigned p>
  12. struct IsPrime {
  13. static constexpr bool value = DoIsPrime < p, p / 2 >::value;
  14. };
  15.  
  16. template<>
  17. struct IsPrime<0> {
  18. static constexpr bool value = false;
  19. };
  20. template<>
  21. struct IsPrime<1> {
  22. static constexpr bool value = false;
  23. };
  24. template<>
  25. struct IsPrime<2> {
  26. static constexpr bool value = true;
  27. };
  28. template<>
  29. struct IsPrime<3> {
  30. static constexpr bool value = true;
  31. };
  32.  
  33. template<unsigned p>
  34. bool isPrime = IsPrime<p>::value;
  35.  
  36. unsigned int p[] = { }
  37.  
  38. template<::std::uint32_t value_upper_bound> constexpr auto
  39. Collect_Primes_Impl(void)
  40. {
  41. static_assert(0 < value_upper_bound);
  42. ::std::array<::std::uint32_t, value_upper_bound> primes{};
  43. primes[0] = 1;
  44. ::std::uint32_t primes_count{1};
  45. ::std::uint32_t value{1};
  46. while(value_upper_bound != value)
  47. {
  48. ++value;
  49. bool is_prime{true};
  50. ::std::uint32_t prime_index{1};
  51. while(primes_count != prime_index)
  52. {
  53. if(0 == (value % primes[prime_index]))
  54. {
  55. is_prime = false;
  56. break;
  57. }
  58. ++prime_index;
  59. }
  60. if(is_prime)
  61. {
  62. primes[primes_count] = value;
  63. ++primes_count;
  64. }
  65. }
  66. return ::std::make_pair(primes_count, primes);
  67. }
  68.  
  69. template<::std::uint32_t value_upper_bound> constexpr auto
  70. Collect_Primes(void)
  71. {
  72. static_assert(0 < value_upper_bound);
  73. constexpr const auto collected{Collect_Primes_Impl<value_upper_bound>()};
  74. ::std::array<::std::uint32_t, collected.first> primes{};
  75. ::std::uint32_t prime_index{0};
  76. while(collected.first != prime_index)
  77. {
  78. primes[prime_index] = collected.second[prime_index];
  79. ++prime_index;
  80. }
  81. return primes;
  82. }
  83.  
  84. constexpr const auto pr20{Collect_Primes<20>()};
  85.  
  86. static_assert(::std::size_t{9} == pr20.size());
  87.  
  88. static_assert(::std::uint32_t{ 1} == pr20[0]);
  89. static_assert(::std::uint32_t{ 2} == pr20[1]);
  90. static_assert(::std::uint32_t{ 3} == pr20[2]);
  91. static_assert(::std::uint32_t{ 5} == pr20[3]);
  92. static_assert(::std::uint32_t{ 7} == pr20[4]);
  93. static_assert(::std::uint32_t{11} == pr20[5]);
  94. static_assert(::std::uint32_t{13} == pr20[6]);
  95. static_assert(::std::uint32_t{17} == pr20[7]);
  96. static_assert(::std::uint32_t{19} == pr20[8]);
Add Comment
Please, Sign In to add comment