Problems with logic in a program

Asked

Viewed 38 times

0

    //EXERCICIO 103
    //VERIFICAR SE UM NÚMERO É PRIMO

    #include<stdio.h>
    #include<locale.h>
    main(){
        setlocale(LC_ALL,"");
        int n,k,cont,div;
        printf("Informe um número: ");
        scanf("%d",&n);

        if(n>0){              //SE n FOR MAIOR QUE 0, O PROGRAMA EXECUTA
            for(k=n; k>0 ;k--){ 
                div = n % k;   //DIVIDE PARA VERIFICAR SE É EXATA 
                if(div==0){  //SE FOR EXATA ADICIONA 1 NO CONTADOR
                    cont++;
                }
            }

            if(cont==2){
                printf("%d é primo.",n);
            }
            else{
                printf("%d não é primo",n);
            }

        }
        else{
            printf("Número inválido!");
        }
    }

I have tested the program several times and tested the logic, apparently it is right but always returns that the number is not prime. I can’t find the mistake, please help me.

  • Initialize the container variable before entering the loop. cont = 0

  • It came right, thank you

  • Much more efficient: https://answall.com/a/85568/101. This further https://answall.com/a/50500/101.

1 answer

0

Paul, to use the command cont++, the variable must have been initialized first. To solve the problem, simply initialize the variable at the beginning of the code, as zero for example: cont = 0;

  • Thanks! I didn’t know I needed to initialize before. It was right.

Browser other questions tagged

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