Hi, I have a question how would i use boost to generate a 160 bit random
integer.
Heres the random number generator i wrote thanks to some of the boost
community help.
#ifndef RANDOM_NUMBER_HPP
#define RANDOM_NUMBER_HPP
#include
#include
#include
#include
#include
#ifdef _linux_
#include
#endif
#include
// credit and thanks to Andrew Holden for help on this.
namespace Random
{
typedef boost::kreutzer1986 base_generator_type;
// typedef boost::mt19937 base_generator_type;
typedef boost::uniform_int<> distribution_type;
typedef boost::variate_generator gen_type;
// boost::random_device nondet_generator;
//Declare the generator as a global variable for easy reuse
#ifdef __linux__
boost::random_device dev;
base_generator_type generator(dev());
#else
base_generator_type generator(GetTickCount());
#endif
/***************************************************
* initializes the random number generator *
**************************************************/
void initialize()
{
for (int i = 0; i < 900; ++i)
{
#ifdef __linux__
generator.seed(dev());
#else
generator.seed(GetTickCount());
#endif
}
}
/***************************************************
* generates a random number between a and b *
* @param a the starting range *
* @param b the integer ending range *
* @return N such that a <= N <= b *
**************************************************/
template <class T>
T randint (const T& a, const T& b)
{
//Check the parameters
BOOST_STATIC_ASSERT(boost::is_integral<T>::value);
assert (b >= a);
//Set up the desired distribution
gen_type ran_gen(generator, distribution_type(a, b));
//Get a random number
return ran_gen();
}
}
#endif /* RANDOM_NUMBER_HPP */
Heres a code to generate random prime number.
/***************************************************
* n <- random number with num_digits digits *
* if n is even then n = n + 1; *
* while is_prime(n, 150) *
* { *
* n = n + 2; *
* } *
* return n; *
***************************************************/
template <typename T>
T boost::random_prime(boost::function f, const
unsigned int& num_digits)
{
BOOST_STATIC_ASSERT(is_integral<T>::value);
T n(Random::randint<T>(numeric_cast<T>(pow(2.0, num_digits - 1)),
numeric_cast<T>(pow(2.0, num_digits)))
);
if (n%2 == 0)
{
++n;
}
while (f(n, 20))
{
n += 2;
}
return n;
}
now num_digits is number of bits. If i pass 160 bit as like for DSA
algorithm the program crashes. I pass 8 and it works, how come? Is there a
better way to do this? Oh f is any function that can deteremine if a number
is most likely a prime or not....
Thanks.