test_gcd.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. // Copyright Jeremy Murphy 2016.
  2. // Use, modification and distribution are subject to the
  3. // Boost Software License, Version 1.0. (See accompanying file
  4. // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  5. #ifdef _MSC_VER
  6. # pragma warning (disable : 4224)
  7. #endif
  8. #include <boost/math/common_factor_rt.hpp>
  9. #include <boost/math/special_functions/prime.hpp>
  10. #include <boost/multiprecision/cpp_int.hpp>
  11. #include <boost/multiprecision/integer.hpp>
  12. #include <boost/random.hpp>
  13. #include <boost/array.hpp>
  14. #include <iostream>
  15. #include <algorithm>
  16. #include <numeric>
  17. #include <string>
  18. #include <tuple>
  19. #include <type_traits>
  20. #include <vector>
  21. #include <functional>
  22. #include "fibonacci.hpp"
  23. #include "../../test/table_type.hpp"
  24. #include "table_helper.hpp"
  25. #include "performance.hpp"
  26. using namespace std;
  27. boost::multiprecision::cpp_int total_sum(0);
  28. template <typename Func, class Table>
  29. double exec_timed_test_foo(Func f, const Table& data, double min_elapsed = 0.5)
  30. {
  31. double t = 0;
  32. unsigned repeats = 1;
  33. typename Table::value_type::first_type sum{0};
  34. stopwatch<boost::chrono::high_resolution_clock> w;
  35. do
  36. {
  37. for(unsigned count = 0; count < repeats; ++count)
  38. {
  39. for(typename Table::size_type n = 0; n < data.size(); ++n)
  40. sum += f(data[n].first, data[n].second);
  41. }
  42. t = boost::chrono::duration_cast<boost::chrono::duration<double>>(w.elapsed()).count();
  43. if(t < min_elapsed)
  44. repeats *= 2;
  45. }
  46. while(t < min_elapsed);
  47. total_sum += sum;
  48. return t / repeats;
  49. }
  50. template <typename T>
  51. struct test_function_template
  52. {
  53. vector<pair<T, T> > const & data;
  54. const char* data_name;
  55. test_function_template(vector<pair<T, T> > const &data, const char* name) : data(data), data_name(name) {}
  56. template <typename Function>
  57. void operator()(pair<Function, string> const &f) const
  58. {
  59. auto result = exec_timed_test_foo(f.first, data);
  60. auto table_name = string("gcd method comparison with ") + compiler_name() + string(" on ") + platform_name();
  61. report_execution_time(result,
  62. table_name,
  63. string(data_name),
  64. string(f.second) + "\n" + boost_name());
  65. }
  66. };
  67. boost::random::mt19937 rng;
  68. boost::random::uniform_int_distribution<> d_0_6(0, 6);
  69. boost::random::uniform_int_distribution<> d_1_20(1, 20);
  70. template <class T>
  71. T get_prime_products()
  72. {
  73. int n_primes = d_0_6(rng);
  74. switch(n_primes)
  75. {
  76. case 0:
  77. // Generate a power of 2:
  78. return static_cast<T>(1u) << d_1_20(rng);
  79. case 1:
  80. // prime number:
  81. return boost::math::prime(d_1_20(rng) + 3);
  82. }
  83. T result = 1;
  84. for(int i = 0; i < n_primes; ++i)
  85. result *= boost::math::prime(d_1_20(rng) + 3) * boost::math::prime(d_1_20(rng) + 3) * boost::math::prime(d_1_20(rng) + 3) * boost::math::prime(d_1_20(rng) + 3) * boost::math::prime(d_1_20(rng) + 3);
  86. return result;
  87. }
  88. template <class T>
  89. T get_uniform_random()
  90. {
  91. static boost::random::uniform_int_distribution<T> minmax((std::numeric_limits<T>::min)(), (std::numeric_limits<T>::max)());
  92. return minmax(rng);
  93. }
  94. template <class T>
  95. inline bool even(T const& val)
  96. {
  97. return !(val & 1u);
  98. }
  99. template <class Backend, boost::multiprecision::expression_template_option ExpressionTemplates>
  100. inline bool even(boost::multiprecision::number<Backend, ExpressionTemplates> const& val)
  101. {
  102. return !bit_test(val, 0);
  103. }
  104. template <class T>
  105. T euclid_textbook(T a, T b)
  106. {
  107. using std::swap;
  108. if(a < b)
  109. swap(a, b);
  110. while(b)
  111. {
  112. T t = b;
  113. b = a % b;
  114. a = t;
  115. }
  116. return a;
  117. }
  118. template <class T>
  119. T binary_textbook(T u, T v)
  120. {
  121. if(u && v)
  122. {
  123. unsigned shifts = (std::min)(boost::multiprecision::lsb(u), boost::multiprecision::lsb(v));
  124. if(shifts)
  125. {
  126. u >>= shifts;
  127. v >>= shifts;
  128. }
  129. while(u)
  130. {
  131. unsigned bit_index = boost::multiprecision::lsb(u);
  132. if(bit_index)
  133. {
  134. u >>= bit_index;
  135. }
  136. else if(bit_index = boost::multiprecision::lsb(v))
  137. {
  138. v >>= bit_index;
  139. }
  140. else
  141. {
  142. if(u < v)
  143. v = (v - u) >> 1u;
  144. else
  145. u = (u - v) >> 1u;
  146. }
  147. }
  148. return v << shifts;
  149. }
  150. return u + v;
  151. }
  152. template <typename Integer>
  153. inline BOOST_CXX14_CONSTEXPR Integer gcd_default(Integer a, Integer b) BOOST_GCD_NOEXCEPT(Integer)
  154. {
  155. using boost::math::gcd;
  156. return gcd(a, b);
  157. }
  158. template <class T>
  159. void test_type(const char* name)
  160. {
  161. using namespace boost::math::gcd_detail;
  162. typedef T int_type;
  163. std::vector<pair<int_type, int_type> > data;
  164. for(unsigned i = 0; i < 1000; ++i)
  165. {
  166. data.push_back(std::make_pair(get_prime_products<T>(), get_prime_products<T>()));
  167. }
  168. std::string row_name("gcd<");
  169. row_name += name;
  170. row_name += "> (random prime number products)";
  171. typedef pair< function<int_type(int_type, int_type)>, string> f_test;
  172. array<f_test, 6> test_functions{ {
  173. { gcd_default<int_type>, "gcd" },
  174. { Euclid_gcd<int_type>, "Euclid_gcd" },
  175. { Stein_gcd<int_type>, "Stein_gcd" } ,
  176. { mixed_binary_gcd<int_type>, "mixed_binary_gcd" },
  177. { binary_textbook<int_type>, "Stein_gcd_textbook" },
  178. { euclid_textbook<int_type>, "gcd_euclid_textbook" },
  179. } };
  180. for_each(begin(test_functions), end(test_functions), test_function_template<int_type>(data, row_name.c_str()));
  181. data.clear();
  182. for(unsigned i = 0; i < 1000; ++i)
  183. {
  184. data.push_back(std::make_pair(get_uniform_random<T>(), get_uniform_random<T>()));
  185. }
  186. row_name.erase();
  187. row_name += "gcd<";
  188. row_name += name;
  189. row_name += "> (uniform random numbers)";
  190. for_each(begin(test_functions), end(test_functions), test_function_template<int_type>(data, row_name.c_str()));
  191. // Fibonacci number tests:
  192. row_name.erase();
  193. row_name += "gcd<";
  194. row_name += name;
  195. row_name += "> (adjacent Fibonacci numbers)";
  196. for_each(begin(test_functions), end(test_functions), test_function_template<int_type>(fibonacci_numbers_permution_1<T>(), row_name.c_str()));
  197. row_name.erase();
  198. row_name += "gcd<";
  199. row_name += name;
  200. row_name += "> (permutations of Fibonacci numbers)";
  201. for_each(begin(test_functions), end(test_functions), test_function_template<int_type>(fibonacci_numbers_permution_2<T>(), row_name.c_str()));
  202. row_name.erase();
  203. row_name += "gcd<";
  204. row_name += name;
  205. row_name += "> (Trivial cases)";
  206. for_each(begin(test_functions), end(test_functions), test_function_template<int_type>(trivial_gcd_test_cases<T>(), row_name.c_str()));
  207. }
  208. /*******************************************************************************************************************/
  209. template <class T>
  210. T generate_random(unsigned bits_wanted)
  211. {
  212. static boost::random::mt19937 gen;
  213. typedef boost::random::mt19937::result_type random_type;
  214. T max_val;
  215. unsigned digits;
  216. if(std::numeric_limits<T>::is_bounded && (bits_wanted == (unsigned)std::numeric_limits<T>::digits))
  217. {
  218. max_val = (std::numeric_limits<T>::max)();
  219. digits = std::numeric_limits<T>::digits;
  220. }
  221. else
  222. {
  223. max_val = T(1) << bits_wanted;
  224. digits = bits_wanted;
  225. }
  226. unsigned bits_per_r_val = std::numeric_limits<random_type>::digits - 1;
  227. while((random_type(1) << bits_per_r_val) > (gen.max)()) --bits_per_r_val;
  228. unsigned terms_needed = digits / bits_per_r_val + 1;
  229. T val = 0;
  230. for(unsigned i = 0; i < terms_needed; ++i)
  231. {
  232. val *= (gen.max)();
  233. val += gen();
  234. }
  235. val %= max_val;
  236. return val;
  237. }
  238. template <typename N>
  239. N gcd_stein(N m, N n)
  240. {
  241. BOOST_ASSERT(m >= static_cast<N>(0));
  242. BOOST_ASSERT(n >= static_cast<N>(0));
  243. if(m == N(0)) return n;
  244. if(n == N(0)) return m;
  245. // m > 0 && n > 0
  246. unsigned d_m = 0;
  247. while(even(m)) { m >>= 1; d_m++; }
  248. unsigned d_n = 0;
  249. while(even(n)) { n >>= 1; d_n++; }
  250. // odd(m) && odd(n)
  251. while(m != n) {
  252. if(n > m) swap(n, m);
  253. m -= n;
  254. do m >>= 1; while(even(m));
  255. // m == n
  256. }
  257. return m << (std::min)(d_m, d_n);
  258. }
  259. boost::multiprecision::cpp_int big_gcd(const boost::multiprecision::cpp_int& a, const boost::multiprecision::cpp_int& b)
  260. {
  261. return boost::multiprecision::gcd(a, b);
  262. }
  263. namespace boost { namespace multiprecision { namespace backends {
  264. template <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>
  265. inline typename enable_if_c<!is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value>::type
  266. eval_gcd_new(
  267. cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& result,
  268. const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& a,
  269. const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& b)
  270. {
  271. using default_ops::eval_lsb;
  272. using default_ops::eval_is_zero;
  273. using default_ops::eval_get_sign;
  274. if(a.size() == 1)
  275. {
  276. eval_gcd(result, b, *a.limbs());
  277. return;
  278. }
  279. if(b.size() == 1)
  280. {
  281. eval_gcd(result, a, *b.limbs());
  282. return;
  283. }
  284. int shift;
  285. cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> u(a), v(b), mod;
  286. int s = eval_get_sign(u);
  287. /* GCD(0,x) := x */
  288. if(s < 0)
  289. {
  290. u.negate();
  291. }
  292. else if(s == 0)
  293. {
  294. result = v;
  295. return;
  296. }
  297. s = eval_get_sign(v);
  298. if(s < 0)
  299. {
  300. v.negate();
  301. }
  302. else if(s == 0)
  303. {
  304. result = u;
  305. return;
  306. }
  307. /* Let shift := lg K, where K is the greatest power of 2
  308. dividing both u and v. */
  309. unsigned us = eval_lsb(u);
  310. unsigned vs = eval_lsb(v);
  311. shift = (std::min)(us, vs);
  312. eval_right_shift(u, us);
  313. eval_right_shift(v, vs);
  314. // From now on access u and v via pointers, that way we have a trivial swap:
  315. cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>* up(&u), *vp(&v), *mp(&mod);
  316. do
  317. {
  318. /* Now u and v are both odd, so diff(u, v) is even.
  319. Let u = min(u, v), v = diff(u, v)/2. */
  320. s = up->compare(*vp);
  321. if(s > 0)
  322. std::swap(up, vp);
  323. if(s == 0)
  324. break;
  325. if(vp->size() <= 2)
  326. {
  327. if(vp->size() == 1)
  328. *up = boost::math::gcd_detail::mixed_binary_gcd(*vp->limbs(), *up->limbs());
  329. else
  330. {
  331. double_limb_type i, j;
  332. i = vp->limbs()[0] | (static_cast<double_limb_type>(vp->limbs()[1]) << sizeof(limb_type) * CHAR_BIT);
  333. j = (up->size() == 1) ? *up->limbs() : up->limbs()[0] | (static_cast<double_limb_type>(up->limbs()[1]) << sizeof(limb_type) * CHAR_BIT);
  334. u = boost::math::gcd_detail::mixed_binary_gcd(i, j);
  335. }
  336. break;
  337. }
  338. if(vp->size() > up->size() /*eval_msb(*vp) > eval_msb(*up) + 32*/)
  339. {
  340. eval_modulus(*mp, *vp, *up);
  341. std::swap(vp, mp);
  342. eval_subtract(*up, *vp);
  343. if(eval_is_zero(*vp) == 0)
  344. {
  345. vs = eval_lsb(*vp);
  346. eval_right_shift(*vp, vs);
  347. }
  348. else
  349. break;
  350. if(eval_is_zero(*up) == 0)
  351. {
  352. vs = eval_lsb(*up);
  353. eval_right_shift(*up, vs);
  354. }
  355. else
  356. {
  357. std::swap(up, vp);
  358. break;
  359. }
  360. }
  361. else
  362. {
  363. eval_subtract(*vp, *up);
  364. vs = eval_lsb(*vp);
  365. eval_right_shift(*vp, vs);
  366. }
  367. }
  368. while(true);
  369. result = *up;
  370. eval_left_shift(result, shift);
  371. }
  372. }}}
  373. boost::multiprecision::cpp_int big_gcd_new(const boost::multiprecision::cpp_int& a, const boost::multiprecision::cpp_int& b)
  374. {
  375. boost::multiprecision::cpp_int result;
  376. boost::multiprecision::backends::eval_gcd_new(result.backend(), a.backend(), b.backend());
  377. return result;
  378. }
  379. #if 0
  380. void test_n_bits(unsigned n, std::string data_name, const std::vector<pair<boost::multiprecision::cpp_int, boost::multiprecision::cpp_int> >* p_data = 0)
  381. {
  382. using namespace boost::math::detail;
  383. typedef boost::multiprecision::cpp_int int_type;
  384. std::vector<pair<int_type, int_type> > data, data2;
  385. for(unsigned i = 0; i < 1000; ++i)
  386. {
  387. data.push_back(std::make_pair(generate_random<int_type>(n), generate_random<int_type>(n)));
  388. }
  389. typedef pair< function<int_type(int_type, int_type)>, string> f_test;
  390. array<f_test, 2> test_functions{ { /*{ Stein_gcd<int_type>, "Stein_gcd" } ,{ Euclid_gcd<int_type>, "Euclid_gcd" },{ binary_textbook<int_type>, "Stein_gcd_textbook" },{ euclid_textbook<int_type>, "gcd_euclid_textbook" },{ mixed_binary_gcd<int_type>, "mixed_binary_gcd" },{ gcd_stein<int_type>, "gcd_stein" },*/{ big_gcd, "boost::multiprecision::gcd" },{ big_gcd_new, "big_gcd_new" } } };
  391. for_each(begin(test_functions), end(test_functions), test_function_template<int_type>(p_data ? *p_data : data, data_name.c_str(), true));
  392. }
  393. #endif
  394. int main()
  395. {
  396. test_type<unsigned short>("unsigned short");
  397. test_type<unsigned>("unsigned");
  398. test_type<unsigned long>("unsigned long");
  399. test_type<unsigned long long>("unsigned long long");
  400. test_type<boost::multiprecision::uint256_t>("boost::multiprecision::uint256_t");
  401. test_type<boost::multiprecision::uint512_t>("boost::multiprecision::uint512_t");
  402. test_type<boost::multiprecision::uint1024_t>("boost::multiprecision::uint1024_t");
  403. /*
  404. test_n_bits(16, " 16 bit random values");
  405. test_n_bits(32, " 32 bit random values");
  406. test_n_bits(64, " 64 bit random values");
  407. test_n_bits(125, " 125 bit random values");
  408. test_n_bits(250, " 250 bit random values");
  409. test_n_bits(500, " 500 bit random values");
  410. test_n_bits(1000, " 1000 bit random values");
  411. test_n_bits(5000, " 5000 bit random values");
  412. test_n_bits(10000, "10000 bit random values");
  413. //test_n_bits(100000);
  414. //test_n_bits(1000000);
  415. test_n_bits(0, "consecutive first 1000 fibonacci numbers", &fibonacci_numbers_cpp_int_permution_1());
  416. test_n_bits(0, "permutations of first 1000 fibonacci numbers", &fibonacci_numbers_cpp_int_permution_2());
  417. */
  418. return 0;
  419. }