C # - Random prime numbers?

4

I have a college exercise that is to generate a random primal number, if that number is not prime it must be generating another random one until one is, but it always falls into numbers that are not prime and are in infinite loop, the What am I doing wrong in the code? Thanks in advance for your help.

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

            }

        }
    
asked by anonymous 22.10.2017 / 21:29

2 answers

2

Just as @Thiago has already said, you have in fact failed to put the splitters (the variable div ) to 0 at the end of while . However structuring with functions turns out to be simpler and this problem is not possible either.

See the same structured program with a cousin check 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 a lot of cousin checking optimizations that could be done, but they are a little bit off the point.

    
23.10.2017 / 00:39
4

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

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

    
22.10.2017 / 22:00