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"
13 /// Generate a sequences of primes p_i such that \prod_i p_i < limit
14 static std::vector<cln::cl_I>
15 make_random_moduli(const cln::cl_I& limit);
17 static std::vector<cln::cl_I>
18 calc_residues(const cln::cl_I& x, const std::vector<cln::cl_I>& moduli);
20 static void dump(const std::vector<cln::cl_I>& v);
22 /// Make @a n random relatively prime moduli, each < limit, make a
23 /// random number x < \prod_{i=0}{n-1}, calculate residues, and
24 /// compute x' by chinese remainder algorithm. Check if the result
25 /// of computation matches the original value x.
26 static void run_test_once(const cln::cl_I& lim)
28 std::vector<cln::cl_I> moduli = make_random_moduli(lim);
29 cln::cl_I x = random_I(lim) + 1;
34 std::vector<cln::cl_I> residues = calc_residues(x, moduli);
39 x_test = integer_cra(residues, moduli);
40 } catch (std::exception& oops) {
41 std::cerr << "Oops: " << oops.what() << std::endl;
49 std::cerr << "Expected x = " << x << ", got " <<
50 x_test << " instead" << std::endl;
51 std::cerr << "moduli = ";
53 std::cerr << std::endl;
54 std::cerr << "residues = ";
56 std::cerr << std::endl;
57 throw std::logic_error("bug in integer_cra?");
61 static void run_test(const cln::cl_I& limit, const std::size_t ntimes)
63 for (std::size_t i = 0; i < ntimes; ++i)
67 int main(int argc, char** argv)
69 typedef std::map<cln::cl_I, std::size_t> map_t;
71 // Run 1024 tests with native 32-bit numbers
72 the_map[cln::cl_I(std::numeric_limits<int>::max())] = 1024;
74 // Run 512 tests with native 64-bit integers
75 if (sizeof(long) > sizeof(int))
76 the_map[cln::cl_I(std::numeric_limits<long>::max())] = 512;
78 // Run 32 tests with a bit bigger numbers
79 the_map[cln::cl_I("987654321098765432109876543210")] = 32;
81 std::cout << "examining Garner's integer chinese remainder algorithm " << std::flush;
83 for (map_t::const_iterator i = the_map.begin(); i != the_map.end(); ++i)
84 run_test(i->first, i->second);
89 static std::vector<cln::cl_I>
90 calc_residues(const cln::cl_I& x, const std::vector<cln::cl_I>& moduli)
92 std::vector<cln::cl_I> residues(moduli.size());
93 for (std::size_t i = moduli.size(); i-- != 0; )
94 residues[i] = mod(x, moduli[i]);
98 static std::vector<cln::cl_I>
99 make_random_moduli(const cln::cl_I& limit)
101 std::vector<cln::cl_I> moduli;
103 cln::cl_I next = random_I(std::min(limit >> 1, cln::cl_I(128)));
105 cln::cl_I tmp = nextprobprime(next);
106 next = tmp + random_I(cln::cl_I(10)) + 1;
108 moduli.push_back(tmp);
109 } while (prod < limit);
113 static void dump(const std::vector<cln::cl_I>& v)
116 for (std::size_t i = 0; i < v.size(); ++i)
117 std::cerr << v[i] << " ";