Use wheel factorization for prime numbers
Certain existing units in the library require very large prime numbers---so large, in fact, that our naive trial division hits the _iteration limit_ for `constexpr` loops. We don't want to force users to provide a compiler option override, so we'd better find another way. The solution is to use the "wheel factorization" algorithm: https://en.wikipedia.org/wiki/Wheel_factorization This lets us skip most composite numbers in our trial division. The implementation presented here is configurable in terms of the size of the "basis" of primes we use. Bigger bases let us skip more primes, but at the cost of storing more numbers. Fortunately, it turns out that N=3 was good enough for our purposes.
This commit is contained in:
1 parent
2198c8a403
commit
04b80f0827
5 files changed
+218
-21
No files matched your search
@@ -140,6 +140,15 @@ TEST_CASE("make_ratio performs prime factorization correctly")
|
||||
// The failure was due to a prime factor which is larger than 2^31.
|
||||
as_magnitude<ratio(16'605'390'666'050, 10'000'000'000'000)>();
|
||||
}
|
||||
|
||||
SECTION("Can handle prime number which would exceed GCC iteration limit")
|
||||
{
|
||||
// GCC 10 has a constexpr loop iteration limit of 262144. A naive algorithm, which performs trial division on 2 and
|
||||
// all odd numbers up to sqrt(N), will exceed this limit for the following prime. Thus, for this test to pass, we
|
||||
// need to be using a more efficient algorithm. (We could increase the limit, but we don't want users to have to
|
||||
// mess with compiler flags just to compile the code.)
|
||||
as_magnitude<334524384739>();
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("magnitude converts to numerical value")
|
||||
@@ -344,15 +353,6 @@ TEST_CASE("int_power computes integer powers") {
|
||||
|
||||
TEST_CASE("Prime helper functions")
|
||||
{
|
||||
SECTION("find_first_factor()") {
|
||||
CHECK(find_first_factor(1) == 1);
|
||||
CHECK(find_first_factor(2) == 2);
|
||||
CHECK(find_first_factor(4) == 2);
|
||||
CHECK(find_first_factor(6) == 2);
|
||||
CHECK(find_first_factor(15) == 3);
|
||||
CHECK(find_first_factor(17) == 17);
|
||||
}
|
||||
|
||||
SECTION("multiplicity") {
|
||||
CHECK(multiplicity(2, 8) == 3);
|
||||
CHECK(multiplicity(2, 1024) == 10);
|
||||
|
||||
Reference in new issue
Block a user