Skip to content

Commit

Permalink
Address review feedback
Browse files Browse the repository at this point in the history
  • Loading branch information
chiphogg committed Nov 12, 2024
1 parent aa8896c commit 12aa23e
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
11 changes: 7 additions & 4 deletions au/code/au/utility/probable_primes.hh
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@

#pragma once

#include <cmath>

#include "au/utility/mod.hh"

namespace au {
Expand Down Expand Up @@ -91,9 +93,10 @@ constexpr uint64_t gcd(uint64_t a, uint64_t b) {
return a;
}

// The conversions `true` -> `1` and `false` -> `0` are guaranteed by the standard.
// Map `true` onto `1`, and `false` onto `0`.
//
// This is a branchless implementation, which should generally be faster.
// The conversions `true` -> `1` and `false` -> `0` are guaranteed by the standard. This is a
// branchless implementation, which should generally be faster.
constexpr int bool_sign(bool x) { return x - (!x); }

//
Expand All @@ -113,7 +116,7 @@ constexpr int bool_sign(bool x) { return x - (!x); }
// either a or n is congruent to 1 (mod 4), and 1 otherwise.
//
constexpr int jacobi_symbol_positive_numerator(uint64_t a, uint64_t n, int start) {
int &result = start;
int result = start;

while (a != 0u) {
// Handle even numbers in the "numerator".
Expand Down Expand Up @@ -155,7 +158,7 @@ constexpr int jacobi_symbol(int64_t raw_a, uint64_t n) {
// Starting conditions: transform `a` to strictly non-negative values, setting `result` to the
// sign we pick up from this operation (if any).
int result = bool_sign((raw_a >= 0) || (n % 4u == 1u));
auto a = static_cast<uint64_t>(raw_a * bool_sign(raw_a >= 0)) % n;
auto a = static_cast<uint64_t>(std::abs(raw_a)) % n;

// Delegate to an implementation which can only handle positive numbers.
return jacobi_symbol_positive_numerator(a, n, result);
Expand Down
10 changes: 10 additions & 0 deletions au/code/au/utility/test/probable_primes_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,16 @@ TEST(JacobiSymbol, AlwaysOneWhenFirstInputIsOne) {
}
}

TEST(JacobiSymbol, ReproducesExamplesFromWikipedia) {
// https://en.wikipedia.org/wiki/Jacobi_symbol#Example_of_calculations
EXPECT_EQ(jacobi_symbol(1001, 9907), -1);

// https://en.wikipedia.org/wiki/Jacobi_symbol#Primality_testing
EXPECT_EQ(jacobi_symbol(19, 45), 1);
EXPECT_EQ(jacobi_symbol(8, 21), -1);
EXPECT_EQ(jacobi_symbol(5, 21), 1);
}

TEST(BoolSign, ReturnsCorrectValues) {
EXPECT_EQ(bool_sign(true), 1);
EXPECT_EQ(bool_sign(false), -1);
Expand Down

0 comments on commit 12aa23e

Please sign in to comment.