From d16656919753438a57a32f9ad6ba972c25d66b11 Mon Sep 17 00:00:00 2001 From: Sebastiano Tronto Date: Sun, 9 Feb 2025 19:38:26 +0100 Subject: Added random number generator for bigint --- README.md | 4 +++- bigint.h | 13 +++++++++++++ random_bigint | 34 ++++++++++++++++++++++++++++++++++ 3 files changed, 50 insertions(+), 1 deletion(-) create mode 100755 random_bigint diff --git a/README.md b/README.md index 043b626..1d4a3f9 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,9 @@ Usage: ## BigInt This repo contains also a class for big integer. Performance are not great, -but you have a look at it for educational purposes. +but you can have a look at it for educational purposes. + +The script `random_bigint` can be used to generate random big integers. ## Development diff --git a/bigint.h b/bigint.h index 9287fda..096ed9c 100644 --- a/bigint.h +++ b/bigint.h @@ -3,6 +3,7 @@ #include #include +#include #include constexpr uint64_t abs64(int64_t); @@ -123,6 +124,18 @@ public: constexpr BigInt operator/=(const BigInt& z) { return *this = *this / z; } constexpr BigInt operator%=(const BigInt& z) { return *this = *this % z; } + static BigInt random(BigInt r) { + std::random_device rd; + std::default_random_engine rng(rd()); + std::uniform_int_distribution distribution(0, M-1); + + BigInt ret; + for (uint64_t i = 0; i < D; i++) + ret.digits[i] = distribution(rng); + + return ret % r; + } + friend std::ostream& operator<<(std::ostream& os, const BigInt& z) { if (z == 0) { 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 @@ +#if 0 + +cc=${CC:-g++} +bin="$(mktemp)" + +if [ -z "$1" ] || [ -z "$2" ]; then + echo "Usage: $0 m n" + echo "Example: to generate 5 random 25-digits number use" + echo " $0 \\\"10000000000000000000000000\\\" 5" + exit 1 +fi + +${cc} -x c++ -std=c++20 -o "$bin" -g -O0 "$(realpath $0)" \ + -DMAX_RANDOM="$1" -DHOW_MANY="$2" +echo "Running $bin" +"$bin" + +exit 0 +#endif + +#include "bigint.h" + +#include + +int main() { + // Read compile-time variables + int n = HOW_MANY; + BigInt<100> r(MAX_RANDOM); + + for (int i = 0; i < n; i++) + std::cout << BigInt<100>::random(r) << std::endl; + + return 0; +} -- cgit v1.2.3