C# - Random primes?

Asked

Viewed 943 times

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);

            }

        }

2 answers

4

You forgot to reset the number of splitters to 0 at each while iteration start.

Since the variable is only used in one place, it would be clearer if you declared it inside the while.

  • 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.

  • 1

    You can accept the answer as valid if it helped. :)

  • 1

    Learning the functionalities of the site also, answer more accepted, thanks again for the help !!!

3


As @Thiago has already said, it has in fact missed putting the dividers back (the variable div) to 0 at the end of while. However structuring with functions ends up being simpler and this problem is not even possible to happen.

See the same structured program with a prime verification function:

public static bool ePrimo(int num){
    int div = 0;

    for (int i = 1; i <= num; i++)
    {
        if (num % i == 0)
        {
            div++;
        }   
    }

    return div == 2; //true se div for 2, falso caso contrário
}

public static void Main()
{
    Random r = new Random();
    int p = r.Next(1, 100);

    //aqui testa se não é primo, e executa enquanto não for primo
    while (!ePrimo(p)) 
    {
        p = r.Next(1,100);
    }

    Console.WriteLine(p);
}

See this example in . NET Fiddle

There were still many optimizations of the cousin’s verification that could do, but already flee a little from the focus of the question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.