5
I have a college exercise that is to generate a random prime number, if that number is not prime it should keep generating another random until one is, but it always falls into numbers that are not prime and are in infinite loop, what am I doing wrong in the code? Thank you in advance for your help.
Follows code below:
static void Main(string[] args)
{
int p, div = 0;
bool nPrimo = false;
Random r = new Random();
p = r.Next(1, 100);
while (nPrimo == false)
{
for (int i = 1; i <= p; i++)
{
if (p % i == 0)
{
div++;
}
}
if (div == 2)
{
nPrimo = true;
}
else
{
p = r.Next(1,100);
}
}
Vlw !!! was such a simple business and I was cracking my head. And thanks for the tip about the variable, I’ll do it this way.
– Felipe Lourenço
You can accept the answer as valid if it helped. :)
– Thiago Barcala
Learning the functionalities of the site also, answer more accepted, thanks again for the help !!!
– Felipe Lourenço