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;
}
Exit:
0 is not cousin
1 is not cousin
3 is cousin yes
2 is cousin yes
4 is not cousin
5 is cousin yes
7 is cousin yes
9 is not cousin
This function IsPrime()
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 check calculation within the same loop that reads the values typed by the user, it is always a good way to create separate functions to perform certain tasks, this way you can reuse it and use it elsewhere.
And we also have to ensure the treatment of the numbers typed by the user, so the use of unsigned
for unsigned numbers, and validation of the number at the beginning, however, it is necessary to do other validations of the data before sending to the function IsPrime()
verify the number.
See working on Ideone.
Source.
remember to assign 0 to the div variable.
– Felipe