Skip to content

mod_sqrt.hpp

SECTIONMath INCLUDEnoya/mod_sqrt.hpp

Compute the smaller square root modulo a prime, or nullopt if no square root exists.

Verified by sqrt_mod.

\[ \displaystyle x^2\equiv a\pmod p \]

Implementation

View on GitHub

#ifndef NOYA_MOD_SQRT_HPP
#define NOYA_MOD_SQRT_HPP 1

/// @complexity Time: O(log^2 p).
/// Space: O(1).

#include "noya/factorize.hpp"

#include <algorithm>
#include <cassert>
#include <cstdint>
#include <optional>

namespace noya {

/// @brief Compute the smaller square root modulo a prime, or nullopt if no
/// square root exists.
inline std::optional<std::uint64_t> mod_sqrt(std::uint64_t value,
                                             std::uint64_t modulus) {
  assert(modulus >= 2 && is_prime(modulus));
  value %= modulus;
  if (modulus == 2 || value == 0) {
    return value;
  }
  using factorize_internal::multiply_mod;
  using factorize_internal::power_mod;
  if (power_mod(value, (modulus - 1) / 2, modulus) != 1) {
    return std::nullopt;
  }
  if (modulus % 4 == 3) {
    std::uint64_t root = power_mod(value, (modulus + 1) / 4, modulus);
    return std::min(root, modulus - root);
  }

  std::uint64_t odd = modulus - 1;
  int exponent = 0;
  while ((odd & 1) == 0) {
    odd >>= 1;
    exponent++;
  }
  std::uint64_t non_residue = 2;
  while (power_mod(non_residue, (modulus - 1) / 2, modulus) != modulus - 1) {
    non_residue++;
  }

  std::uint64_t root = power_mod(value, (odd + 1) / 2, modulus);
  std::uint64_t remainder = power_mod(value, odd, modulus);
  std::uint64_t step = power_mod(non_residue, odd, modulus);
  int remaining = exponent;
  while (remainder != 1) {
    std::uint64_t squared = remainder;
    int shift = 0;
    while (squared != 1 && shift < remaining) {
      squared = multiply_mod(squared, squared, modulus);
      shift++;
    }
    assert(shift < remaining);
    std::uint64_t multiplier =
        power_mod(step, std::uint64_t(1) << (remaining - shift - 1), modulus);
    root = multiply_mod(root, multiplier, modulus);
    step = multiply_mod(multiplier, multiplier, modulus);
    remainder = multiply_mod(remainder, step, modulus);
    remaining = shift;
  }
  return std::min(root, modulus - root);
}

} // namespace noya

#endif // NOYA_MOD_SQRT_HPP
#include <algorithm>
#include <array>
#include <cassert>
#include <cstdint>
#include <numeric>
#include <optional>
#include <utility>
#include <vector>

/// @complexity Time: O(log^2 p).
/// Space: O(1).

/// @complexity Time: O(log^3 n) primality testing; Pollard-rho factorization is expected about O(n^(1/4)).
/// Space: O(log n) recursion and factors.

namespace noya {
namespace factorize_internal {

using u64 = std::uint64_t;
using u128 = unsigned __int128;

inline u64 multiply_mod(u64 a, u64 b, u64 mod) {
  return u64(u128(a) * b % mod);
}

inline u64 power_mod(u64 a, u64 exponent, u64 mod) {
  u64 result = 1;
  while (exponent > 0) {
    if (exponent & 1) {
      result = multiply_mod(result, a, mod);
    }
    a = multiply_mod(a, a, mod);
    exponent >>= 1;
  }
  return result;
}

inline bool miller_rabin(u64 n) {
  if (n < 2) {
    return false;
  }
  for (u64 p :
       std::array<u64, 12>{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37}) {
    if (n % p == 0) {
      return n == p;
    }
  }
  int shift = __builtin_ctzll(n - 1);
  u64 odd = (n - 1) >> shift;
  for (u64 base :
       std::array<u64, 7>{2, 325, 9375, 28178, 450775, 9780504, 1795265022}) {
    if (base % n == 0) {
      continue;
    }
    u64 value = power_mod(base % n, odd, n);
    if (value == 1 || value == n - 1) {
      continue;
    }
    bool composite = true;
    for (int i = 1; i < shift; i++) {
      value = multiply_mod(value, value, n);
      if (value == n - 1) {
        composite = false;
        break;
      }
    }
    if (composite) {
      return false;
    }
  }
  return true;
}

inline u64 splitmix64(u64 &state) {
  u64 z = (state += 0x9e3779b97f4a7c15ULL);
  z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ULL;
  z = (z ^ (z >> 27)) * 0x94d049bb133111ebULL;
  return z ^ (z >> 31);
}

inline u64 pollard_rho(u64 n) {
  if (n % 2 == 0) {
    return 2;
  }
  if (n % 3 == 0) {
    return 3;
  }
  static u64 state = 0x123456789abcdef0ULL;
  while (true) {
    u64 y = splitmix64(state) % (n - 1) + 1;
    u64 c = splitmix64(state) % (n - 1) + 1;
    constexpr u64 block = 128;
    u64 g = 1;
    u64 r = 1;
    u64 q = 1;
    u64 x = 0;
    u64 saved_y = 0;
    auto next = [&](u64 value) {
      return u64((u128(multiply_mod(value, value, n)) + c) % n);
    };
    while (g == 1) {
      x = y;
      for (u64 i = 0; i < r; i++) {
        y = next(y);
      }
      for (u64 offset = 0; offset < r && g == 1; offset += block) {
        saved_y = y;
        for (u64 i = 0; i < std::min(block, r - offset); i++) {
          y = next(y);
          u64 difference = x > y ? x - y : y - x;
          q = multiply_mod(q, difference, n);
        }
        g = std::gcd(q, n);
      }
      r <<= 1;
    }
    if (g == n) {
      do {
        saved_y = next(saved_y);
        u64 difference = x > saved_y ? x - saved_y : saved_y - x;
        g = std::gcd(difference, n);
      } while (g == 1);
    }
    if (g != n) {
      return g;
    }
  }
}

inline void collect_factors(u64 n, std::vector<u64> &result) {
  if (n == 1) {
    return;
  }
  if (miller_rabin(n)) {
    result.push_back(n);
    return;
  }
  u64 factor = pollard_rho(n);
  collect_factors(factor, result);
  collect_factors(n / factor, result);
}

} // namespace factorize_internal

/// @brief Deterministic Miller-Rabin primality test for unsigned 64-bit
/// integers.
inline bool is_prime(std::uint64_t n) {
  return factorize_internal::miller_rabin(n);
}

/// @brief Return the prime factors of n with multiplicity in increasing order.
inline std::vector<std::uint64_t> prime_factors(std::uint64_t n) {
  assert(n >= 1);
  std::vector<std::uint64_t> result;
  factorize_internal::collect_factors(n, result);
  std::sort(result.begin(), result.end());
  return result;
}

/// @brief Return the prime factorization of n as (prime, exponent) pairs.
inline std::vector<std::pair<std::uint64_t, int>> factorize(std::uint64_t n) {
  std::vector<std::pair<std::uint64_t, int>> result;
  for (std::uint64_t p : prime_factors(n)) {
    if (result.empty() || result.back().first != p) {
      result.emplace_back(p, 1);
    } else {
      result.back().second++;
    }
  }
  return result;
}

} // namespace noya

namespace noya {

/// @brief Compute the smaller square root modulo a prime, or nullopt if no
/// square root exists.
inline std::optional<std::uint64_t> mod_sqrt(std::uint64_t value,
                                             std::uint64_t modulus) {
  assert(modulus >= 2 && is_prime(modulus));
  value %= modulus;
  if (modulus == 2 || value == 0) {
    return value;
  }
  using factorize_internal::multiply_mod;
  using factorize_internal::power_mod;
  if (power_mod(value, (modulus - 1) / 2, modulus) != 1) {
    return std::nullopt;
  }
  if (modulus % 4 == 3) {
    std::uint64_t root = power_mod(value, (modulus + 1) / 4, modulus);
    return std::min(root, modulus - root);
  }

  std::uint64_t odd = modulus - 1;
  int exponent = 0;
  while ((odd & 1) == 0) {
    odd >>= 1;
    exponent++;
  }
  std::uint64_t non_residue = 2;
  while (power_mod(non_residue, (modulus - 1) / 2, modulus) != modulus - 1) {
    non_residue++;
  }

  std::uint64_t root = power_mod(value, (odd + 1) / 2, modulus);
  std::uint64_t remainder = power_mod(value, odd, modulus);
  std::uint64_t step = power_mod(non_residue, odd, modulus);
  int remaining = exponent;
  while (remainder != 1) {
    std::uint64_t squared = remainder;
    int shift = 0;
    while (squared != 1 && shift < remaining) {
      squared = multiply_mod(squared, squared, modulus);
      shift++;
    }
    assert(shift < remaining);
    std::uint64_t multiplier =
        power_mod(step, std::uint64_t(1) << (remaining - shift - 1), modulus);
    root = multiply_mod(root, multiplier, modulus);
    step = multiply_mod(multiplier, multiplier, modulus);
    remainder = multiply_mod(remainder, step, modulus);
    remaining = shift;
  }
  return std::min(root, modulus - root);
}

} // namespace noya