2 #include <cln/integer.h>
3 #include <cln/integer_io.h>
4 #include <cln/random.h>
5 #include <cln/numtheory.h>
6 #include "polynomial/cra_garner.hpp"
14 /// Generate a sequences of primes p_i such that \prod_i p_i < limit
15 static std::vector<cln::cl_I>
16 make_random_moduli(const cln::cl_I& limit);
18 static std::vector<cln::cl_I>
19 calc_residues(const cln::cl_I& x, const std::vector<cln::cl_I>& moduli);
21 static void dump(const std::vector<cln::cl_I>& v);
23 /// Make @a n random relatively prime moduli, each < limit, make a
24 /// random number x < \prod_{i=0}{n-1}, calculate residues, and
25 /// compute x' by chinese remainder algorithm. Check if the result
26 /// of computation matches the original value x.
27 static void run_test_once(const cln::cl_I& lim)
29 std::vector<cln::cl_I> moduli = make_random_moduli(lim);
30 cln::cl_I x = random_I(lim) + 1;
35 std::vector<cln::cl_I> residues = calc_residues(x, moduli);
40 x_test = integer_cra(residues, moduli);
41 } catch (std::exception& oops) {
42 std::cerr << "Oops: " << oops.what() << std::endl;
50 std::cerr << "Expected x = " << x << ", got " <<
51 x_test << " instead" << std::endl;
52 std::cerr << "moduli = ";
54 std::cerr << std::endl;
55 std::cerr << "residues = ";
57 std::cerr << std::endl;
58 throw std::logic_error("bug in integer_cra?");
62 static void run_test(const cln::cl_I& limit, const std::size_t ntimes)
64 for (std::size_t i = 0; i < ntimes; ++i)
68 int main(int argc, char** argv)
70 typedef std::map<cln::cl_I, std::size_t> map_t;
72 // Run 1024 tests with native 32-bit numbers
73 the_map[cln::cl_I(std::numeric_limits<int>::max())] = 1024;
75 // Run 512 tests with native 64-bit integers
76 if (sizeof(long) > sizeof(int))
77 the_map[cln::cl_I(std::numeric_limits<long>::max())] = 512;
79 // Run 32 tests with a bit bigger numbers
80 the_map[cln::cl_I("987654321098765432109876543210")] = 32;
82 std::cout << "examining Garner's integer chinese remainder algorithm " << std::flush;
84 for (map_t::const_iterator i = the_map.begin(); i != the_map.end(); ++i)
85 run_test(i->first, i->second);
90 static std::vector<cln::cl_I>
91 calc_residues(const cln::cl_I& x, const std::vector<cln::cl_I>& moduli)
93 std::vector<cln::cl_I> residues(moduli.size());
94 for (std::size_t i = moduli.size(); i-- != 0; )
95 residues[i] = mod(x, moduli[i]);
99 static std::vector<cln::cl_I>
100 make_random_moduli(const cln::cl_I& limit)
102 std::vector<cln::cl_I> moduli;
104 cln::cl_I next = random_I(std::min(limit >> 1, cln::cl_I(128)));
106 cln::cl_I tmp = nextprobprime(next);
107 next = tmp + random_I(cln::cl_I(10)) + 1;
109 moduli.push_back(tmp);
110 } while (prod < limit);
114 static void dump(const std::vector<cln::cl_I>& v)
117 for (std::size_t i = 0; i < v.size(); ++i)
118 std::cerr << v[i] << " ";