You can use this function to check if the number is prime:
#include <stdio.h>
/* Retorna 1 para numeros primo ou 0 para numeros que nao sao primos.*/
int IsPrime(unsigned int number) {
if (number <= 1) return 0; // se o numero for menor ou igual a 1 então nao é primo.
unsigned int i;
for (i = 2; i * i <= number; i++) {
if (number % i == 0) return 0;
}
return 1;
}
int main(void) {
printf("0 é primo %s\n", IsPrime(0) ? "sim" : "nao");
printf("1 é primo %s\n", IsPrime(1) ? "sim" : "nao");
printf("3 é primo %s\n", IsPrime(3) ? "sim" : "nao");
printf("2 é primo %s\n", IsPrime(2) ? "sim" : "nao");
printf("4 é primo %s\n", IsPrime(4) ? "sim" : "nao");
printf("5 é primo %s\n", IsPrime(5) ? "sim" : "nao");
printf("7 é primo %s\n", IsPrime(7) ? "sim" : "nao");
printf("9 é primo %s\n", IsPrime(9) ? "sim" : "nao");
return 0;
}
Output:
0 is not prime cousin
1 is not a cousin
3 is prime cousin
2 is prime cousin
4 is not a cousin
5 is prime cousin
7 is prime cousin
9 is prime not
This IsPrime()
function can be easily used in a loop, and will not have a high maintenance cost, see:
int i, v;
for(i = 0; i < 5; i++) {
printf("Informe um numero: ");
scanf("%i", &v);
printf("%i é primo %s\n",v , IsPrime(v) ? "sim" : "nao");
}
It is not necessary to do the number verification calculation inside the same loop that reads the values entered by the user, it is always a good way to create separate functions to perform certain tasks, in this way you can reuse it and use it in other places.
And we also have to guarantee the treatment of the numbers entered by the user, so the use of unsigned
for unsigned numbers, and the validation of the number at the beginning, however, it is necessary to make other validations of the data before sending to the IsPrime()
function checks the number.
See working at Ideone .
Font .