abacus: add initial bignum library
This commit is contained in:
parent
ff35faa705
commit
12c8b6b114
37
src/bignum/bignum.cc
Normal file
37
src/bignum/bignum.cc
Normal file
|
@ -0,0 +1,37 @@
|
|||
#include "bignum.hh"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
#include <cmath>
|
||||
|
||||
namespace abacus::bignum {
|
||||
|
||||
BigNum::BigNum(std::int64_t number) {
|
||||
if (number == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (number < 0) {
|
||||
sign_ = -1;
|
||||
} else {
|
||||
sign_ = 1;
|
||||
}
|
||||
|
||||
auto abs = static_cast<std::uint64_t>(std::abs(number));
|
||||
do {
|
||||
digits_.push_back(abs % 10);
|
||||
abs /= 10;
|
||||
} while (abs);
|
||||
}
|
||||
|
||||
void BigNum::canonicalize() {
|
||||
auto const it = std::find_if(digits_.rbegin(), digits_.rend(),
|
||||
[](auto v) { return v != 0; });
|
||||
digits_.erase(it.base(), digits_.end());
|
||||
|
||||
if (digits_.size() == 0) {
|
||||
sign_ = 0;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace abacus::bignum
|
20
src/bignum/bignum.hh
Normal file
20
src/bignum/bignum.hh
Normal file
|
@ -0,0 +1,20 @@
|
|||
#pragma once
|
||||
|
||||
#include <vector>
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace abacus::bignum {
|
||||
|
||||
class BigNum {
|
||||
public:
|
||||
explicit BigNum(std::int64_t number);
|
||||
|
||||
private:
|
||||
void canonicalize();
|
||||
|
||||
std::vector<std::uint8_t> digits_{};
|
||||
int sign_ = 0;
|
||||
};
|
||||
|
||||
} // namespace abacus::bignum
|
16
src/bignum/meson.build
Normal file
16
src/bignum/meson.build
Normal file
|
@ -0,0 +1,16 @@
|
|||
bignum_sources = files(
|
||||
'bignum.cc',
|
||||
'bignum.hh',
|
||||
)
|
||||
|
||||
bignum_inc = include_directories('.')
|
||||
|
||||
bignum_lib = library(
|
||||
'bignum',
|
||||
sources: bignum_sources,
|
||||
)
|
||||
|
||||
bignum = declare_dependency(
|
||||
link_with: bignum_lib,
|
||||
include_directories: bignum_inc,
|
||||
)
|
|
@ -2,6 +2,7 @@ abacus_sources = files(
|
|||
'abacus.cc',
|
||||
)
|
||||
|
||||
subdir('bignum')
|
||||
subdir('parse')
|
||||
|
||||
abacus = executable(
|
||||
|
|
Loading…
Reference in a new issue