- Joined
- Oct 12, 2011
- Messages
- 3,449
hello guys, I have question here: how can I generate random integer in c++? I tried to use rand() % upperBound but it always return a same value if I call it several times D: any solution? thanks!
/* rand example: guess the number */
#include <stdio.h> /* printf, scanf, puts, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
int main ()
{
int iSecret, iGuess;
/* initialize random seed: */
srand (time(NULL));
/* generate secret number between 1 and 10: */
iSecret = rand() % 10 + 1;
do {
printf ("Guess the number (1 to 10): ");
scanf ("%d",&iGuess);
if (iSecret<iGuess) puts ("The secret number is lower");
else if (iSecret>iGuess) puts ("The secret number is higher");
} while (iSecret!=iGuess);
puts ("Congratulations!");
return 0;
}
it causes compile error for me :/ it says time identifier not found..srand (time(NULL));
int RandomPrime()
{
srand(time(NULL));
int i = rand() % upperBound;
while (i < lowerBound)
i = rand() % upperBound;
while (!IsPrime(i))
{
i = rand() % upperBound;
while (i < lowerBound)
i = rand() % upperBound;
}
return i;
}
i = lowerBound + rand() % (upperBound - lowerBound + 1);
okay, I will try it.Don't call srand each time, call it once when the program starts.
checkTo remove those ugly loops, use:
upperbound is 800 lower bound is 100. IsPrime works correctly, here is the codeAs to the function in general, what are the values of upper and lower bounds? how does IsPrime work?
bool IsPrime(int n)
{
for(int i = 2; i < n; i++)
if (n%i == 0)
return false;
return true;
}
you are right sir! but I only need random prime twice, again it's problem about memory wise or speed wiseAnd if what you want is a prime, a much better way would probably be to generate an array of primes once, and select a random index every time you want one.
rand
) will always return the same sequence of values given the same seed. If you indeed get the same values on every run, then the seed never changes.srand
, and people generally use time(NULL)
as the seed since that returns an integer representation of the current computer time, which keeps changing.printf
'ing your seed.int random_int_between_zero_and_ten() {
std::random_device device;
std::mt19937 engine(device()); // seeding the engine.
std::uniform_int_distribution<int> dist(0, 10); // define a uniform distribution for numbers between 0 and 10
return dist(engine); // Passing the engine to the distribution's operator() will generate your number.
}