aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--README.md4
-rw-r--r--bigint.h13
-rwxr-xr-xrandom_bigint34
3 files changed, 50 insertions, 1 deletions
diff --git a/README.md b/README.md
index 043b626..1d4a3f9 100644
--- a/README.md
+++ b/README.md
@@ -10,7 +10,9 @@ Usage:
10## BigInt 10## BigInt
11 11
12This repo contains also a class for big integer. Performance are not great, 12This repo contains also a class for big integer. Performance are not great,
13but you have a look at it for educational purposes. 13but you can have a look at it for educational purposes.
14
15The script `random_bigint` can be used to generate random big integers.
14 16
15## Development 17## Development
16 18
diff --git a/bigint.h b/bigint.h
index 9287fda..096ed9c 100644
--- a/bigint.h
+++ b/bigint.h
@@ -3,6 +3,7 @@
3 3
4#include <cstdint> 4#include <cstdint>
5#include <iostream> 5#include <iostream>
6#include <random>
6#include <string_view> 7#include <string_view>
7 8
8constexpr uint64_t abs64(int64_t); 9constexpr uint64_t abs64(int64_t);
@@ -123,6 +124,18 @@ public:
123 constexpr BigInt operator/=(const BigInt& z) { return *this = *this / z; } 124 constexpr BigInt operator/=(const BigInt& z) { return *this = *this / z; }
124 constexpr BigInt operator%=(const BigInt& z) { return *this = *this % z; } 125 constexpr BigInt operator%=(const BigInt& z) { return *this = *this % z; }
125 126
127 static BigInt random(BigInt r) {
128 std::random_device rd;
129 std::default_random_engine rng(rd());
130 std::uniform_int_distribution<int> distribution(0, M-1);
131
132 BigInt ret;
133 for (uint64_t i = 0; i < D; i++)
134 ret.digits[i] = distribution(rng);
135
136 return ret % r;
137 }
138
126 friend std::ostream& operator<<(std::ostream& os, const BigInt<N, E>& z) { 139 friend std::ostream& operator<<(std::ostream& os, const BigInt<N, E>& z) {
127 if (z == 0) { 140 if (z == 0) {
128 os << "0"; 141 os << "0";
diff --git a/random_bigint b/random_bigint
new file mode 100755
index 0000000..250de64
--- /dev/null
+++ b/random_bigint
@@ -0,0 +1,34 @@
1#if 0
2
3cc=${CC:-g++}
4bin="$(mktemp)"
5
6if [ -z "$1" ] || [ -z "$2" ]; then
7 echo "Usage: $0 m n"
8 echo "Example: to generate 5 random 25-digits number use"
9 echo " $0 \\\"10000000000000000000000000\\\" 5"
10 exit 1
11fi
12
13${cc} -x c++ -std=c++20 -o "$bin" -g -O0 "$(realpath $0)" \
14 -DMAX_RANDOM="$1" -DHOW_MANY="$2"
15echo "Running $bin"
16"$bin"
17
18exit 0
19#endif
20
21#include "bigint.h"
22
23#include <iostream>
24
25int main() {
26 // Read compile-time variables
27 int n = HOW_MANY;
28 BigInt<100> r(MAX_RANDOM);
29
30 for (int i = 0; i < n; i++)
31 std::cout << BigInt<100>::random(r) << std::endl;
32
33 return 0;
34}