algorithm that finds prime numbers in an interval

Asked

Viewed 254 times

0

I’m having trouble with this code, I’ve seen it in many places how to fix it, but I can’t really find the error, it prints out values of the whole range, not just primes.

// The program will inform the user of prime numbers in a defined interval

int main () 
{
    int a,b,n,cont,primo;

    printf("Digite o infimo e o supremo de um intervalo, separados por espaço:\n");
    scanf("%i %i", &a, &b);

    if (a > b)
        printf("erro\n");
    else
        for (cont = a; cont <= b; cont++){
            primo = 0;
            for(n = 1; n <= cont; n++){
                if(cont % n == 0);
                    primo++;
            }
            if(primo == 2)
                printf("%d\n", cont);    
        }
   return 0;
}

1 answer

1

Typo:

                if(cont % n == 0);
                    primo++;

The problem is the semicolon at the end of the if that shouldn’t be there.

Ah, and as an observation, the variable primo you should actually call yourself divisores_encontrados or something like that, once she counts how many dividers cont has, and not how many prime numbers have been found.

  • Caraca, gave it right, thank you very much. Just one more doubt, in terms of syntax , as the ; is interpreted, because this difference occurs. Again thanks for the help!

  • @Victor O ; is interpreted as an empty instruction that does nothing, which means that the primo++; it’s actually after the if, and not inside it.

  • @Víctorvianna If this answer solved your problem and there is no doubt left, click on " " which is to the left of the answer to mark it as accepted/correct, which also marks your question as solved/answered. Otherwise, feel free to comment.

Browser other questions tagged

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