Infinite loop trying to calculate whether the number is prime

6

I have no idea how I will determine the condition of for for prime numbers. I always end up in looping .

#include <stdio.h>

    int main() {

    int num = 1, primo;
    do {

            printf("Informe um numero primo maior que 1:");
           scanf("%d", &primo);

       } while (primo <= 1);



           for(num=1; num<=primo; primo++){

           if(primo%num==0)
           printf("Numero primo",primo);
           else
           printf("Numero não primo",primo);}

   }
    
asked by anonymous 06.09.2015 / 06:07

2 answers

7

To program you have to think of everything as the problem really is. It's no use kicking things. This is not programming. One of the things that helps to clarify the thoughts is to keep the code well organized, easy to read and understand, including giving names to variables that are meaningful, that indicate what that name actually represents. You have to think about the correct name for everything, otherwise it generates confusion as seen in this code.

You can only know if a number is prime or not after you have tested all possibilities, you can not know by testing each of the possibilities, so the check can not be inside the loop.

#include <stdio.h>

int main() {
    int i, numero;
    do {
        printf("Informe um numero primo maior que 1:");
        scanf("%d", &numero);
    } while (numero <= 1);
    for (i = 2; i < numero; i++) {
        if (numero % i == 0) {
            break;
        }
    }
    if (numero == i) {
        printf("Numero primo %d", numero);
    } else {
        printf("Numero não primo %d", numero);
    }
}

See running on ideone .

    
06.09.2015 / 06:26
0

To check whether a number is prime or not, you do not have to make all checks from 2 to n. Because number 2 is the only prime number, so to check if 11 is prime or not, you only need to check up to 5, because the remaining numbers are multiples of 1, 2, 3, 4, and 5, that is, 3x2 = 6, 4x2 = 8 and 5x2 = 10, since all natural numbers multiplied by 2 are even, so they will not be primes, except for 2. So if you check whether a very large number is prime or not, you will get the fastest result.

int isPrimeNumber(int num){
    if(num <= 1){
        return 0; //Retorna falso
    } else {
        int quant = num / 2;
        for(; quant >= 2; --quant)
            if(num % quant == 0)
                return 0; //Retorna falso
        return 1; //Retorna verdadeiro
    }
}

Non-ideone code: Prime number

    
11.09.2015 / 19:29