zmodn

A simple C++ library for integers modulo N
git clone https://git.tronto.net/zmodn
Download | Log | Files | Refs | README

commit d16656919753438a57a32f9ad6ba972c25d66b11
parent ece9b2e4c547c986fd9e2bb4b7d97287be5621fb
Author: Sebastiano Tronto <sebastiano@tronto.net>
Date:   Sun,  9 Feb 2025 19:38:26 +0100

Added random number generator for bigint

Diffstat:
MREADME.md | 4+++-
Mbigint.h | 13+++++++++++++
Arandom_bigint | 34++++++++++++++++++++++++++++++++++
3 files changed, 50 insertions(+), 1 deletion(-)

diff --git 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 @@ -3,6 +3,7 @@ #include <cstdint> #include <iostream> +#include <random> #include <string_view> 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<int> 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<N, E>& z) { if (z == 0) { os << "0"; diff --git a/random_bigint 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 <iostream> + +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; +}