Your problem, as the other answers pointed out, is that you are subtracting 1
from i
and then by doing an operation involving i - 1
. The most straightforward way to resolve this is to move the decrement from i
to the end:
while (i>1){
b=a/(i-1);
//i=i-1; // <-- Sai daqui...
if (a%(i-1)==0){
printf ("Nao Primo");
}else
printf ("Primo");
i=i-1; // <-- ...e vem pra cá.
}
I would also suggest stopping in
2
instead of
1
, otherwise you will eventually
a % 1
which is always
0
(i.e., the program will say that every number is "No cousin").
Also, there are two other "weird" things in your code:
With each test the program will print "Primo"
or "Nao Primo"
. If you test with 6
for example the output will be:
Primo
Primo
Nao primo
Nao primo
Primo
Instead, put in a variable whether the number is prime or not, and only print the result at the end of the test:
int primo = 1; // Na falta de informação em contrário, todo número é primo
i=a;
while (i>2){
b=a/(i-1);
if (a%(i-1)==0){
primo = 0; // Agora sabemos com certeza que não é primo
}
// Não precisa do else, se não achamos um divisor ele continua como está
i=i-1;
}
if (primo == 0){
printf ("Nao Primo");
}else
printf ("Primo");
The variable b
is never used, so what do you need it for? It can be removed.
Otherwise, there is the use of break
- which you may not have learned yet. Spoiler: It serves to stop an early loop. If inside if
you put an additional statement - break;
- so now that he knows for sure that the number is not prime he does not have to continue testing, he stops right there. There is also a way to stop earlier without using break
:
while (i>2 && primo != 0){
That is, only continue if the i
is greater than 2
And the number is not proven non-prime.