#line 1 "verify/utilities/int512.test.cpp"
#define PROBLEM "https://judge.yosupo.jp/problem/many_aplusb"
#include <cassert>
#include <limits>
#include <random>
#include <sstream>
#include <stdexcept>
#include <string>
#include <utility>
#line 1 "utilities/fast_io.hpp"
#include <algorithm>
#include <array>
#include <cerrno>
#include <charconv>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstdint>
#include <cstring>
#include <iterator>
#line 15 "utilities/fast_io.hpp"
#include <sys/stat.h>
#include <type_traits>
#line 18 "utilities/fast_io.hpp"
#include <unistd.h>
#include <vector>
namespace m1une {
namespace utilities {
struct FastOutput;
namespace internal {
// Shared with the convenience helpers in template.hpp.
inline FastOutput* standard_output_instance = nullptr;
// Detect std::begin(x), std::end(x).
template <class T, class = void>
struct is_range : std::false_type {};
template <class T>
struct is_range<T, std::void_t<
decltype(std::begin(std::declval<T&>())),
decltype(std::end(std::declval<T&>()))
>> : std::true_type {};
template <class T>
inline constexpr bool is_range_v = is_range<T>::value;
template <class T>
using range_reference_t = decltype(*std::begin(std::declval<T&>()));
template <class T>
using range_value_t = std::remove_cv_t<std::remove_reference_t<range_reference_t<T>>>;
template <class T, class = void>
struct range_stored_value {
using type = range_value_t<T>;
};
template <class T>
struct range_stored_value<T, std::void_t<typename std::remove_cv_t<std::remove_reference_t<T>>::value_type>> {
using type = typename std::remove_cv_t<std::remove_reference_t<T>>::value_type;
};
template <class T>
using range_stored_value_t = typename range_stored_value<T>::type;
// Treat strings and C strings as scalar output objects, not as ranges.
template <class T>
struct is_char_array : std::false_type {};
template <class T, std::size_t N>
struct is_char_array<T[N]>
: std::bool_constant<std::is_same_v<std::remove_cv_t<T>, char>> {};
template <class T>
struct is_string_like
: std::bool_constant<
std::is_same_v<std::decay_t<T>, std::string>
|| std::is_same_v<std::decay_t<T>, const char*>
|| std::is_same_v<std::decay_t<T>, char*>
|| is_char_array<std::remove_reference_t<T>>::value
> {};
template <class T>
inline constexpr bool is_string_like_v = is_string_like<T>::value;
// ModInt-like type: x.val() is printable, and x can be assigned from long long.
template <class T, class = void>
struct has_val_method : std::false_type {};
template <class T>
struct has_val_method<T, std::void_t<decltype(std::declval<const T&>().val())>>
: std::true_type {};
template <class T>
inline constexpr bool has_val_method_v = has_val_method<T>::value;
template <class T, class = void>
struct has_static_mod_raw : std::false_type {};
template <class T>
struct has_static_mod_raw<
T, std::void_t<decltype(T::mod()), decltype(T::raw(std::declval<uint32_t>()))>>
: std::true_type {};
template <class T>
inline constexpr bool has_static_mod_raw_v = has_static_mod_raw<T>::value;
// libstdc++ before GCC 16 does not classify __int128 as an integral type in
// strict ISO modes such as -std=c++23. Keep the fast-I/O interface independent
// of that implementation detail.
template <class T>
inline constexpr bool is_integral_v =
std::is_integral_v<T>
|| std::is_same_v<std::remove_cv_t<T>, __int128_t>
|| std::is_same_v<std::remove_cv_t<T>, __uint128_t>;
template <class T>
inline constexpr bool is_signed_v =
std::is_signed_v<T>
|| std::is_same_v<std::remove_cv_t<T>, __int128_t>;
template <class T>
struct make_unsigned {
using type = std::make_unsigned_t<T>;
};
template <>
struct make_unsigned<__int128_t> {
using type = __uint128_t;
};
template <>
struct make_unsigned<__uint128_t> {
using type = __uint128_t;
};
template <class T>
using make_unsigned_t = typename make_unsigned<std::remove_cv_t<T>>::type;
} // namespace internal
struct FastInput {
static constexpr int buffer_size = 1 << 20;
private:
std::FILE* _stream;
char _buffer[buffer_size];
int _position;
int _length;
int _file_descriptor;
bool _streaming;
bool refill() {
_position = 0;
if (_streaming) {
ssize_t length;
do {
length = ::read(_file_descriptor, _buffer, buffer_size);
} while (length < 0 && errno == EINTR);
if (length <= 0) {
_length = 0;
return false;
}
_length = int(length);
} else {
_length = int(std::fread(_buffer, 1, buffer_size, _stream));
}
return _length != 0;
}
template <class T>
bool read_integer_from_stream(T& value) {
if (!skip_spaces()) return false;
int c = read_char_raw();
bool negative = false;
if (c == '-') {
negative = true;
c = read_char_raw();
}
if constexpr (internal::is_signed_v<T>) {
T result = 0;
while ('0' <= c && c <= '9') {
result = negative ? result * 10 - (c - '0')
: result * 10 + (c - '0');
c = read_char_raw();
}
value = result;
} else {
T result = 0;
while ('0' <= c && c <= '9') {
result = result * 10 + T(c - '0');
c = read_char_raw();
}
value = negative ? T(0) - result : result;
}
return true;
}
bool prepare_number() {
if (_length - _position >= 64) return true;
const int remaining = _length - _position;
if (remaining > 0) std::memmove(_buffer, _buffer + _position, remaining);
const int added = int(std::fread(_buffer + remaining, 1, buffer_size - remaining, _stream));
_position = 0;
_length = remaining + added;
if (_length < buffer_size) _buffer[_length] = '\0';
return _length != 0;
}
public:
explicit FastInput(std::FILE* stream = stdin)
: _stream(stream),
_position(0),
_length(0),
_file_descriptor(::fileno(stream)),
_streaming([&] {
struct stat status;
return _file_descriptor >= 0
&& ::fstat(_file_descriptor, &status) == 0
&& !S_ISREG(status.st_mode);
}()) {}
FastInput(const FastInput&) = delete;
FastInput& operator=(const FastInput&) = delete;
int read_char_raw() {
if (_position == _length && !refill()) return EOF;
return _buffer[_position++];
}
bool skip_spaces() {
int c = read_char_raw();
while (c != EOF && c <= ' ') c = read_char_raw();
if (c == EOF) return false;
--_position;
return true;
}
bool read(char& value) {
if (!skip_spaces()) return false;
value = char(read_char_raw());
return true;
}
bool read(std::string& value) {
if (!skip_spaces()) return false;
value.clear();
while (true) {
const int begin = _position;
while (_position < _length &&
static_cast<unsigned char>(_buffer[_position]) > ' ') {
++_position;
}
value.append(_buffer + begin, _position - begin);
if (_position < _length) {
++_position;
return true;
}
if (!refill()) return true;
}
}
bool read(bool& value) {
int x;
if (!read(x)) return false;
value = x != 0;
return true;
}
template <class T>
std::enable_if_t<
internal::is_integral_v<T>
&& !std::is_same_v<std::remove_cv_t<T>, bool>
&& !std::is_same_v<std::remove_cv_t<T>, char>,
bool
>
read(T& value) {
if (_streaming) return read_integer_from_stream(value);
if (!prepare_number()) return false;
int c = static_cast<unsigned char>(_buffer[_position++]);
while (c <= ' ') c = static_cast<unsigned char>(_buffer[_position++]);
bool negative = false;
if (c == '-') {
negative = true;
c = static_cast<unsigned char>(_buffer[_position++]);
}
if constexpr (internal::is_signed_v<T>) {
T result = 0;
while ('0' <= c && c <= '9') {
const int first = c - '0';
const int second = static_cast<unsigned char>(_buffer[_position]) - '0';
if (0 <= second && second <= 9) {
result = negative ? result * 100 - (first * 10 + second)
: result * 100 + (first * 10 + second);
++_position;
} else {
result = negative ? result * 10 - first : result * 10 + first;
}
c = static_cast<unsigned char>(_buffer[_position++]);
}
value = result;
} else {
T result = 0;
while ('0' <= c && c <= '9') {
const unsigned first = unsigned(c - '0');
const int second = static_cast<unsigned char>(_buffer[_position]) - '0';
if (0 <= second && second <= 9) {
result = result * 100 + T(first * 10 + unsigned(second));
++_position;
} else {
result = result * 10 + T(first);
}
c = static_cast<unsigned char>(_buffer[_position++]);
}
value = negative ? T(0) - result : result;
}
if (_position > _length) _position = _length;
return true;
}
template <class T>
std::enable_if_t<std::is_floating_point_v<T>, bool>
read(T& value) {
if (!skip_spaces()) return false;
int c = read_char_raw();
bool negative = false;
if (c == '-' || c == '+') {
negative = c == '-';
c = read_char_raw();
}
long double result = 0;
while ('0' <= c && c <= '9') {
result = result * 10 + (c - '0');
c = read_char_raw();
}
if (c == '.') {
long double place = 0.1L;
c = read_char_raw();
while ('0' <= c && c <= '9') {
result += (c - '0') * place;
place *= 0.1L;
c = read_char_raw();
}
}
if (c == 'e' || c == 'E') {
c = read_char_raw();
bool exponent_negative = false;
if (c == '-' || c == '+') {
exponent_negative = c == '-';
c = read_char_raw();
}
int exponent = 0;
while ('0' <= c && c <= '9') {
exponent = exponent * 10 + (c - '0');
c = read_char_raw();
}
long double scale = 1;
long double power = 10;
while (exponent > 0) {
if (exponent & 1) scale *= power;
power *= power;
exponent >>= 1;
}
result = exponent_negative ? result / scale : result * scale;
}
value = static_cast<T>(negative ? -result : result);
return true;
}
template <class T>
std::enable_if_t<
internal::has_val_method_v<T>
&& !internal::is_integral_v<T>
&& !internal::is_range_v<T>,
bool
>
read(T& value) {
long long x;
if (!read(x)) return false;
if constexpr (internal::has_static_mod_raw_v<T>) {
if (x >= 0 && uint64_t(x) < uint64_t(T::mod())) {
value = T::raw(uint32_t(x));
} else {
value = T(x);
}
} else {
value = T(x);
}
return true;
}
template <class First, class Second>
bool read(std::pair<First, Second>& value) {
if (!read(value.first)) return false;
return read(value.second);
}
template <class Range>
std::enable_if_t<
internal::is_range_v<Range>
&& !internal::is_string_like_v<Range>,
bool
>
read(Range& range) {
using StoredValue = internal::range_stored_value_t<Range>;
constexpr bool nested = internal::is_range_v<StoredValue>
&& !internal::is_string_like_v<StoredValue>;
for (auto&& value : range) {
if constexpr (std::is_same_v<StoredValue, bool> && !nested) {
bool x;
if (!read(x)) return false;
value = x;
} else {
if (!read(value)) return false;
}
}
return true;
}
template <class First, class Second, class... Rest>
bool read(First& first, Second& second, Rest&... rest) {
if (!read(first)) return false;
return read(second, rest...);
}
template <class T>
FastInput& operator>>(T& value) {
if (!read(value)) std::abort();
return *this;
}
};
struct FastOutput {
static constexpr int buffer_size = 1 << 20;
private:
inline static const auto digit_quads = [] {
std::array<char, 40000> result{};
for (int i = 0; i < 10000; i++) {
int value = i;
for (int j = 3; j >= 0; j--) {
result[4 * i + j] = char('0' + value % 10);
value /= 10;
}
}
return result;
}();
std::FILE* _stream;
char _buffer[buffer_size];
int _position;
int _precision;
std::chars_format _float_format;
char _range_separator;
std::string* _capture = nullptr;
template <class T>
std::string format_cell(const T& value) {
std::string result;
struct CaptureGuard {
std::string*& target;
std::string* previous;
~CaptureGuard() { target = previous; }
} guard{_capture, _capture};
_capture = &result;
write(value);
return result;
}
template <class Matrix>
void write_aligned_matrix(const Matrix& matrix) {
std::vector<std::vector<std::string>> rows;
std::vector<std::size_t> widths;
for (const auto& row : matrix) {
auto& cells = rows.emplace_back();
std::size_t column = 0;
for (const auto& value : row) {
cells.push_back(format_cell(value));
if (column == widths.size()) widths.push_back(0);
widths[column] = std::max(widths[column], cells.back().size());
++column;
}
}
bool first = true;
for (const auto& row : rows) {
if (!first) write_char('\n');
first = false;
for (std::size_t column = 0; column < row.size(); ++column) {
if (column != 0) write_char(_range_separator);
for (std::size_t padding = row[column].size();
padding < widths[column]; ++padding) {
write_char(' ');
}
write(row[column]);
}
}
}
public:
explicit FastOutput(std::FILE* stream = stdout)
: _stream(stream),
_position(0),
_precision(6),
_float_format(std::chars_format::general),
_range_separator(' ') {
if (_stream == stdout
&& internal::standard_output_instance == nullptr) {
internal::standard_output_instance = this;
}
}
FastOutput(const FastOutput&) = delete;
FastOutput& operator=(const FastOutput&) = delete;
~FastOutput() {
flush();
if (internal::standard_output_instance == this) {
internal::standard_output_instance = nullptr;
}
}
void flush() {
if (_position != 0) {
std::fwrite(_buffer, 1, _position, _stream);
_position = 0;
}
std::fflush(_stream);
}
void write_char(char c) {
if (_capture != nullptr) {
_capture->push_back(c);
return;
}
if (_position == buffer_size) flush();
_buffer[_position++] = c;
}
void write(const char* s) {
while (*s != '\0') write_char(*s++);
}
void write(const std::string& s) {
if (_capture != nullptr) {
_capture->append(s);
return;
}
std::size_t position = 0;
while (position < s.size()) {
if (_position == buffer_size) flush();
const std::size_t copied =
std::min<std::size_t>(buffer_size - _position, s.size() - position);
std::memcpy(_buffer + _position, s.data() + position, copied);
_position += int(copied);
position += copied;
}
}
void write(char c) {
write_char(c);
}
void write(bool value) {
write_char(value ? '1' : '0');
}
template <class T>
std::enable_if_t<std::is_floating_point_v<T>>
write(T value) {
char digits[128];
auto [end, error] = std::to_chars(
digits,
digits + sizeof(digits),
value,
_float_format,
_precision
);
if (error != std::errc()) std::abort();
for (const char* pointer = digits; pointer != end; pointer++) {
write_char(*pointer);
}
}
template <class T>
std::enable_if_t<
internal::is_integral_v<T>
&& !std::is_same_v<std::remove_cv_t<T>, bool>
&& !std::is_same_v<std::remove_cv_t<T>, char>
>
write(T value) {
using Raw = std::remove_cv_t<T>;
using Unsigned = internal::make_unsigned_t<Raw>;
Unsigned magnitude;
if constexpr (internal::is_signed_v<Raw>) {
if (value < 0) {
write_char('-');
magnitude = Unsigned(0) - Unsigned(value);
} else {
magnitude = Unsigned(value);
}
} else {
magnitude = value;
}
if (magnitude == 0) {
write_char('0');
return;
}
unsigned chunks[16];
int count = 0;
while (magnitude >= 10000) {
const Unsigned quotient = magnitude / 10000;
chunks[count++] = unsigned(magnitude - quotient * 10000);
magnitude = quotient;
}
if (_capture == nullptr && _position > buffer_size - 64) flush();
char captured[64];
char* const begin = _capture != nullptr ? captured : _buffer + _position;
char* destination = begin;
const unsigned leading = unsigned(magnitude);
const char* first = digit_quads.data() + 4 * leading;
int skip = leading < 10 ? 3 : leading < 100 ? 2 : leading < 1000 ? 1 : 0;
for (; skip < 4; skip++) *destination++ = first[skip];
while (count--) {
const char* digits = digit_quads.data() + 4 * chunks[count];
std::memcpy(destination, digits, 4);
destination += 4;
}
if (_capture != nullptr) {
_capture->append(begin, destination - begin);
} else {
_position += int(destination - begin);
}
}
template <class T>
std::enable_if_t<
internal::has_val_method_v<T>
&& !internal::is_integral_v<T>
&& !internal::is_range_v<T>
>
write(const T& value) {
write(value.val());
}
template <class First, class Second>
void write(const std::pair<First, Second>& value) {
write(value.first);
write_char(' ');
write(value.second);
}
template <class Range>
std::enable_if_t<
internal::is_range_v<Range>
&& !internal::is_string_like_v<Range>
>
write(const Range& range) {
using StoredValue = internal::range_stored_value_t<const Range>;
constexpr bool nested = internal::is_range_v<StoredValue>
&& !internal::is_string_like_v<StoredValue>;
bool first = true;
for (const auto& value : range) {
if (!first) write_char(nested ? '\n' : _range_separator);
first = false;
if constexpr (std::is_same_v<StoredValue, bool> && !nested) {
write(static_cast<bool>(value));
} else {
write(value);
}
}
}
template <class First, class... Rest>
void print(const First& first, const Rest&... rest) {
write(first);
((write_char(' '), write(rest)), ...);
}
void println() {
write_char('\n');
}
void set_precision(int precision) {
_precision = precision;
}
void set_fixed(int precision = 6) {
_float_format = std::chars_format::fixed;
_precision = precision;
}
void set_general(int precision = 6) {
_float_format = std::chars_format::general;
_precision = precision;
}
void set_range_separator(char separator) {
_range_separator = separator;
}
template <class Matrix>
void write_aligned(const Matrix& matrix) {
using Row = internal::range_stored_value_t<const Matrix>;
using Cell = internal::range_stored_value_t<const Row>;
static_assert(internal::is_range_v<Row> && !internal::is_string_like_v<Row>,
"write_aligned requires a two-dimensional range");
static_assert(!internal::is_range_v<Cell> || internal::is_string_like_v<Cell>,
"write_aligned requires scalar cells");
write_aligned_matrix(matrix);
}
template <class Matrix>
void println_aligned(const Matrix& matrix) {
write_aligned(matrix);
write_char('\n');
}
template <class... Args>
void println(const Args&... args) {
print(args...);
write_char('\n');
}
template <class T>
FastOutput& operator<<(const T& value) {
write(value);
return *this;
}
};
} // namespace utilities
} // namespace m1une
#line 1 "utilities/int128.hpp"
#line 5 "utilities/int128.hpp"
#include <cctype>
#include <istream>
#include <ostream>
#line 10 "utilities/int128.hpp"
namespace m1une {
namespace utilities {
using i128 = __int128_t;
using u128 = __uint128_t;
inline std::string to_string(u128 x) {
if (x == 0) {
return "0";
}
std::string s;
while (x > 0) {
s.push_back(static_cast<char>('0' + x % 10));
x /= 10;
}
std::reverse(s.begin(), s.end());
return s;
}
inline std::string to_string(i128 x) {
if (x < 0) {
u128 magnitude = static_cast<u128>(-(x + 1)) + 1;
return "-" + to_string(magnitude);
}
return to_string(static_cast<u128>(x));
}
inline u128 parse_uint128(const std::string& s) {
if (s.empty()) {
throw std::invalid_argument("empty string");
}
u128 value = 0;
for (char c : s) {
if (!std::isdigit(static_cast<unsigned char>(c))) {
throw std::invalid_argument("invalid unsigned __int128 literal");
}
value = value * 10 + static_cast<unsigned>(c - '0');
}
return value;
}
inline i128 parse_int128(const std::string& s) {
if (s.empty()) {
throw std::invalid_argument("empty string");
}
bool negative = s[0] == '-';
std::size_t pos = (s[0] == '-' || s[0] == '+') ? 1 : 0;
if (pos == s.size()) {
throw std::invalid_argument("invalid __int128 literal");
}
i128 value = 0;
for (; pos < s.size(); ++pos) {
char c = s[pos];
if (!std::isdigit(static_cast<unsigned char>(c))) {
throw std::invalid_argument("invalid __int128 literal");
}
int digit = c - '0';
value = value * 10 + (negative ? -digit : digit);
}
return value;
}
} // namespace utilities
} // namespace m1une
inline std::ostream& operator<<(std::ostream& os, __uint128_t x) {
return os << m1une::utilities::to_string(x);
}
inline std::ostream& operator<<(std::ostream& os, __int128_t x) {
return os << m1une::utilities::to_string(x);
}
inline std::istream& operator>>(std::istream& is, __uint128_t& x) {
std::string s;
is >> s;
if (is) {
x = m1une::utilities::parse_uint128(s);
}
return is;
}
inline std::istream& operator>>(std::istream& is, __int128_t& x) {
std::string s;
is >> s;
if (is) {
x = m1une::utilities::parse_int128(s);
}
return is;
}
#line 1 "utilities/int512.hpp"
#line 5 "utilities/int512.hpp"
#include <string_view>
#line 1 "utilities/detail/fixed_int.hpp"
#line 6 "utilities/detail/fixed_int.hpp"
#include <concepts>
#line 16 "utilities/detail/fixed_int.hpp"
namespace m1une {
namespace utilities {
namespace detail {
// A signed two's-complement integer whose arithmetic wraps modulo 2^Bits.
// Public aliases select contest-friendly fixed widths in int*.hpp.
template <std::size_t Bits>
class FixedInt {
static_assert(Bits >= 64);
static_assert(Bits % 64 == 0);
private:
static constexpr std::size_t limb_count = Bits / 64;
using LimbArray = std::array<std::uint64_t, limb_count>;
public:
static constexpr std::size_t bit_width = Bits;
constexpr FixedInt() = default;
template <std::integral Integer>
constexpr FixedInt(Integer value) {
static_assert(sizeof(Integer) <= sizeof(std::uint64_t));
if constexpr (std::signed_integral<Integer>) {
const std::uint64_t extension =
value < 0 ? ~std::uint64_t(0) : std::uint64_t(0);
limbs_.fill(extension);
limbs_[0] = static_cast<std::uint64_t>(
static_cast<std::int64_t>(value)
);
} else {
limbs_[0] = static_cast<std::uint64_t>(value);
}
}
explicit FixedInt(std::string_view text) { read(text); }
FixedInt& operator=(std::string_view text) {
read(text);
return *this;
}
void read(std::string_view text) {
if (text.empty()) {
throw std::invalid_argument("empty fixed-width integer");
}
const bool negative = text.front() == '-';
std::size_t position =
(text.front() == '-' || text.front() == '+') ? 1 : 0;
if (position == text.size()) {
throw std::invalid_argument("invalid fixed-width integer");
}
FixedInt result;
for (; position < text.size(); ++position) {
const char digit = text[position];
if (digit < '0' || digit > '9') {
throw std::invalid_argument("invalid fixed-width integer");
}
result.multiply_unsigned_small(10);
result += FixedInt(static_cast<unsigned>(digit - '0'));
}
*this = negative ? -result : result;
}
constexpr bool is_zero() const {
for (const std::uint64_t limb : limbs_) {
if (limb != 0) return false;
}
return true;
}
constexpr bool is_negative() const {
return (limbs_.back() >> 63) != 0;
}
constexpr int sign() const {
if (is_zero()) return 0;
return is_negative() ? -1 : 1;
}
constexpr FixedInt operator+() const { return *this; }
constexpr FixedInt operator-() const {
FixedInt result;
result.limbs_ = limbs_;
negate_unsigned(result.limbs_);
return result;
}
constexpr FixedInt& operator+=(const FixedInt& other) {
__uint128_t carry = 0;
for (std::size_t index = 0; index < limb_count; ++index) {
const __uint128_t current =
__uint128_t(limbs_[index]) + other.limbs_[index] + carry;
limbs_[index] = static_cast<std::uint64_t>(current);
carry = current >> 64;
}
return *this;
}
constexpr FixedInt& operator-=(const FixedInt& other) {
return *this += -other;
}
constexpr FixedInt& operator*=(const FixedInt& other) {
LimbArray product{};
for (std::size_t first = 0; first < limb_count; ++first) {
__uint128_t carry = 0;
for (
std::size_t second = 0;
first + second < limb_count;
++second
) {
const std::size_t position = first + second;
const __uint128_t current =
__uint128_t(limbs_[first]) * other.limbs_[second] +
product[position] + carry;
product[position] = static_cast<std::uint64_t>(current);
carry = current >> 64;
}
}
limbs_ = product;
return *this;
}
constexpr FixedInt& multiply_small(std::uint64_t value) {
multiply_unsigned_small(value);
return *this;
}
constexpr FixedInt& operator/=(const FixedInt& other) {
return *this = divmod(*this, other).first;
}
constexpr FixedInt& operator%=(const FixedInt& other) {
return *this = divmod(*this, other).second;
}
std::string to_string() const {
if (is_zero()) return "0";
const bool negative = is_negative();
LimbArray magnitude = unsigned_magnitude();
constexpr std::size_t chunk_capacity =
(Bits * 30103 / 100000 + 9) / 9;
std::array<std::uint32_t, chunk_capacity> chunks{};
std::size_t chunk_count = 0;
while (!magnitude_is_zero(magnitude)) {
chunks[chunk_count++] = static_cast<std::uint32_t>(
divide_unsigned_by_small(magnitude, 1000000000)
);
}
std::string result;
result.reserve(chunk_count * 9 + negative);
if (negative) result.push_back('-');
result += std::to_string(chunks[chunk_count - 1]);
char digits[9];
while (--chunk_count != 0) {
std::uint32_t chunk = chunks[chunk_count - 1];
for (int index = 8; index >= 0; --index) {
digits[index] = static_cast<char>('0' + chunk % 10);
chunk /= 10;
}
result.append(digits, 9);
}
return result;
}
friend constexpr std::pair<FixedInt, FixedInt> divmod(
const FixedInt& dividend,
const FixedInt& divisor
) {
if (divisor.is_zero()) {
throw std::domain_error("fixed-width integer division by zero");
}
const bool quotient_negative =
dividend.is_negative() != divisor.is_negative();
const bool remainder_negative = dividend.is_negative();
auto [quotient_limbs, remainder_limbs] = divide_unsigned(
dividend.unsigned_magnitude(), divisor.unsigned_magnitude()
);
FixedInt quotient;
FixedInt remainder;
quotient.limbs_ = quotient_limbs;
remainder.limbs_ = remainder_limbs;
if (quotient_negative) quotient = -quotient;
if (remainder_negative) remainder = -remainder;
return std::make_pair(quotient, remainder);
}
friend constexpr std::pair<FixedInt, std::int64_t> divmod_small(
const FixedInt& dividend,
std::uint32_t divisor
) {
if (divisor == 0) {
throw std::domain_error("fixed-width integer division by zero");
}
LimbArray quotient_limbs = dividend.unsigned_magnitude();
const std::uint64_t unsigned_remainder =
divide_unsigned_by_small(quotient_limbs, divisor);
FixedInt quotient;
quotient.limbs_ = quotient_limbs;
if (dividend.is_negative()) quotient = -quotient;
const std::int64_t remainder = dividend.is_negative()
? -std::int64_t(unsigned_remainder)
: std::int64_t(unsigned_remainder);
return std::make_pair(quotient, remainder);
}
friend constexpr std::int64_t mod_small(
const FixedInt& dividend,
std::uint32_t divisor
) {
if (divisor == 0) {
throw std::domain_error("fixed-width integer division by zero");
}
const bool negative = dividend.is_negative();
const std::uint64_t remainder = negative
? remainder_unsigned_by_small(
dividend.unsigned_magnitude(),
divisor
)
: remainder_unsigned_by_small(
dividend.limbs_, divisor
);
return negative ? -std::int64_t(remainder)
: std::int64_t(remainder);
}
friend constexpr FixedInt operator+(
FixedInt first,
const FixedInt& second
) {
return first += second;
}
friend constexpr FixedInt operator-(
FixedInt first,
const FixedInt& second
) {
return first -= second;
}
friend constexpr FixedInt operator*(
FixedInt first,
const FixedInt& second
) {
return first *= second;
}
friend constexpr FixedInt operator/(
FixedInt first,
const FixedInt& second
) {
return first /= second;
}
friend constexpr FixedInt operator%(
FixedInt first,
const FixedInt& second
) {
return first %= second;
}
friend constexpr bool operator==(
const FixedInt& first,
const FixedInt& second
) = default;
friend constexpr bool operator<(
const FixedInt& first,
const FixedInt& second
) {
const bool first_negative = first.is_negative();
const bool second_negative = second.is_negative();
if (first_negative != second_negative) return first_negative;
return compare_unsigned(first.limbs_, second.limbs_) < 0;
}
friend constexpr bool operator!=(
const FixedInt& first,
const FixedInt& second
) {
return !(first == second);
}
friend constexpr bool operator>(
const FixedInt& first,
const FixedInt& second
) {
return second < first;
}
friend constexpr bool operator<=(
const FixedInt& first,
const FixedInt& second
) {
return !(second < first);
}
friend constexpr bool operator>=(
const FixedInt& first,
const FixedInt& second
) {
return !(first < second);
}
friend std::ostream& operator<<(
std::ostream& output,
const FixedInt& value
) {
return output << value.to_string();
}
friend std::istream& operator>>(
std::istream& input,
FixedInt& value
) {
std::string text;
if (input >> text) value.read(text);
return input;
}
private:
LimbArray limbs_{};
constexpr LimbArray unsigned_magnitude() const {
LimbArray result = limbs_;
if (is_negative()) negate_unsigned(result);
return result;
}
constexpr void multiply_unsigned_small(std::uint64_t value) {
__uint128_t carry = 0;
for (std::size_t index = 0; index < limb_count; ++index) {
const __uint128_t current =
__uint128_t(limbs_[index]) * value + carry;
limbs_[index] = static_cast<std::uint64_t>(current);
carry = current >> 64;
}
}
static constexpr void negate_unsigned(LimbArray& value) {
for (std::uint64_t& limb : value) limb = ~limb;
for (std::size_t index = 0; index < limb_count; ++index) {
if (++value[index] != 0) break;
}
}
static constexpr int compare_unsigned(
const LimbArray& first,
const LimbArray& second
) {
for (std::size_t offset = 0; offset < limb_count; ++offset) {
const std::size_t index = limb_count - 1 - offset;
if (first[index] != second[index]) {
return first[index] < second[index] ? -1 : 1;
}
}
return 0;
}
static constexpr void subtract_unsigned(
LimbArray& first,
const LimbArray& second
) {
std::uint64_t borrow = 0;
for (std::size_t index = 0; index < limb_count; ++index) {
const std::uint64_t previous = first[index];
first[index] -= second[index] + borrow;
const bool addition_overflow =
borrow != 0 && second[index] == ~std::uint64_t(0);
borrow = addition_overflow ||
previous < second[index] + borrow;
}
}
static constexpr void shift_left_one(LimbArray& value) {
std::uint64_t carry = 0;
for (std::size_t index = 0; index < limb_count; ++index) {
const std::uint64_t next_carry = value[index] >> 63;
value[index] = (value[index] << 1) | carry;
carry = next_carry;
}
}
static constexpr std::pair<LimbArray, LimbArray> divide_unsigned(
const LimbArray& dividend,
const LimbArray& divisor
) {
LimbArray quotient{};
LimbArray remainder{};
for (std::size_t offset = 0; offset < Bits; ++offset) {
const std::size_t bit = Bits - 1 - offset;
shift_left_one(remainder);
remainder[0] |=
(dividend[bit / 64] >> (bit % 64)) & std::uint64_t(1);
if (compare_unsigned(remainder, divisor) >= 0) {
subtract_unsigned(remainder, divisor);
quotient[bit / 64] |= std::uint64_t(1) << (bit % 64);
}
}
return std::make_pair(quotient, remainder);
}
static bool magnitude_is_zero(const LimbArray& value) {
for (const std::uint64_t limb : value) {
if (limb != 0) return false;
}
return true;
}
static constexpr std::uint64_t divide_unsigned_by_small(
LimbArray& value,
std::uint32_t divisor
) {
std::uint64_t remainder = 0;
for (std::size_t offset = 0; offset < limb_count; ++offset) {
const std::size_t index = limb_count - 1 - offset;
const std::uint64_t high =
(remainder << 32) | (value[index] >> 32);
const std::uint64_t quotient_high = high / divisor;
remainder = high % divisor;
const std::uint64_t low =
(remainder << 32) | std::uint32_t(value[index]);
const std::uint64_t quotient_low = low / divisor;
remainder = low % divisor;
value[index] = (quotient_high << 32) | quotient_low;
}
return remainder;
}
static constexpr std::uint64_t remainder_unsigned_by_small(
const LimbArray& value,
std::uint32_t divisor
) {
std::uint64_t remainder = 0;
for (std::size_t offset = 0; offset < limb_count; ++offset) {
const std::size_t index = limb_count - 1 - offset;
remainder = ((remainder << 32) | (value[index] >> 32)) % divisor;
remainder =
((remainder << 32) | std::uint32_t(value[index])) % divisor;
}
return remainder;
}
};
} // namespace detail
} // namespace utilities
} // namespace m1une
#line 8 "utilities/int512.hpp"
namespace m1une {
namespace utilities {
using Int512 = detail::FixedInt<512>;
using i512 = Int512;
inline Int512 parse_int512(std::string_view text) {
return Int512(text);
}
inline std::string to_string(const Int512& value) {
return value.to_string();
}
} // namespace utilities
} // namespace m1une
#line 14 "verify/utilities/int512.test.cpp"
namespace {
using m1une::utilities::i128;
using m1une::utilities::Int512;
using m1une::utilities::parse_int512;
using m1une::utilities::to_string;
void test_small_arithmetic() {
static_assert(Int512::bit_width == 512);
static_assert(sizeof(Int512) == 64);
constexpr Int512 six = Int512(2) * Int512(3);
static_assert(six == Int512(6));
constexpr Int512 forty_two = Int512(6).multiply_small(7);
static_assert(forty_two == Int512(42));
static_assert(Int512(-7) < Int512(2));
static_assert((-Int512(-9)).sign() == 1);
assert(Int512().is_zero());
assert(Int512(-123456789).to_string() == "-123456789");
assert(
Int512(std::numeric_limits<long long>::min()).to_string() ==
std::to_string(std::numeric_limits<long long>::min())
);
assert(
Int512(std::numeric_limits<unsigned long long>::max()).to_string() ==
std::to_string(std::numeric_limits<unsigned long long>::max())
);
std::mt19937_64 random(0x73c90a4e9182bd65ULL);
for (int iteration = 0; iteration < 10000; ++iteration) {
const long long first =
static_cast<long long>(random() % 2000000001ULL) - 1000000000;
const long long second =
static_cast<long long>(random() % 2000000001ULL) - 1000000000;
const long long third =
static_cast<long long>(random() % 2000000001ULL) - 1000000000;
const i128 expected =
i128(first) * i128(second) + i128(third);
const Int512 actual = Int512(first) * Int512(second) + third;
assert(actual.to_string() == to_string(expected));
}
}
void test_parsing() {
const std::string positive =
"327339060789614187001318969682759915221664204604306478948329136809"
"613379640467455488327009232590415715088668412756007100921725654588"
"5393053328527589376";
assert(Int512(positive).to_string() == positive);
assert(parse_int512("+0000012345") == Int512(12345));
Int512 value = 7;
value = "-987654321098765432109876543210";
assert(value.to_string() == "-987654321098765432109876543210");
std::istringstream input("123456789012345678901234567890");
input >> value;
assert(value.to_string() == "123456789012345678901234567890");
for (const std::string& invalid : {
std::string(), std::string("+"), std::string("-"),
std::string("12x3")
}) {
bool threw = false;
try {
value.read(invalid);
} catch (const std::invalid_argument&) {
threw = true;
}
assert(threw);
}
}
void test_division() {
static_assert(Int512(7) / Int512(3) == Int512(2));
static_assert(Int512(-7) / Int512(3) == Int512(-2));
static_assert(Int512(-7) % Int512(3) == Int512(-1));
constexpr auto small_division = divmod_small(Int512(-100), 7);
static_assert(small_division.first == Int512(-14));
static_assert(small_division.second == -2);
static_assert(mod_small(Int512(-100), 7) == -2);
std::mt19937_64 random(0x685113e57a4a94f1ULL);
for (int iteration = 0; iteration < 4000; ++iteration) {
const long long dividend =
static_cast<long long>(random() % 2000000000001ULL) -
1000000000000LL;
long long divisor =
static_cast<long long>(random() % 2000001ULL) - 1000000;
if (divisor == 0) divisor = 1;
const std::pair<Int512, Int512> result =
divmod(Int512(dividend), Int512(divisor));
assert(result.first.to_string() == std::to_string(dividend / divisor));
assert(result.second.to_string() == std::to_string(dividend % divisor));
assert(result.first * divisor + result.second == dividend);
const std::uint32_t small_divisor =
static_cast<std::uint32_t>(random()) | 1;
const auto [small_quotient, small_remainder] =
divmod_small(Int512(dividend), small_divisor);
assert(
small_quotient.to_string() ==
std::to_string(dividend / std::int64_t(small_divisor))
);
assert(small_remainder == dividend % std::int64_t(small_divisor));
assert(
mod_small(Int512(dividend), small_divisor) == small_remainder
);
}
const Int512 dividend(
"100000000000000000000000000000000000000000000000000000000000000000"
"000000000000000000000000000000000000000000000000000000000000000001"
);
const Int512 divisor("123456789012345678901234567890123456789");
const auto [quotient, remainder] = divmod(dividend, divisor);
assert(quotient * divisor + remainder == dividend);
assert(remainder >= 0 && remainder < divisor);
const auto [small_quotient, small_remainder] =
divmod_small(dividend, 1000000007);
assert(
small_quotient * Int512(1000000007) + small_remainder == dividend
);
Int512 minimum = 1;
for (int exponent = 0; exponent < 511; ++exponent) minimum *= 2;
assert(minimum / -1 == minimum);
assert(minimum % -1 == 0);
bool threw = false;
try {
static_cast<void>(dividend / 0);
} catch (const std::domain_error&) {
threw = true;
}
assert(threw);
}
void test_high_limbs_and_wraparound() {
Int512 power = 1;
for (int exponent = 0; exponent < 250; ++exponent) power *= 2;
const Int512 power_500 = power * power;
assert(
power_500.to_string() ==
"327339060789614187001318969682759915221664204604306478948329136809"
"613379640467455488327009232590415715088668412756007100921725654588"
"5393053328527589376"
);
assert((-power_500).to_string() == "-" + power_500.to_string());
Int512 minimum = 1;
for (int exponent = 0; exponent < 511; ++exponent) minimum *= 2;
assert(minimum.is_negative());
assert(-minimum == minimum);
const Int512 maximum = minimum - 1;
assert(maximum.sign() == 1);
assert(maximum + 1 == minimum);
}
} // namespace
int main() {
test_small_arithmetic();
test_parsing();
test_division();
test_high_limbs_and_wraparound();
m1une::utilities::FastInput input;
m1une::utilities::FastOutput output;
int test_count;
input >> test_count;
while (test_count--) {
long long first, second;
input >> first >> second;
output << (Int512(first) + Int512(second)).to_string() << '\n';
}
}