Your problem, as the other answers pointed out, is that you’re subtracting 1
of i
and afterward doing an operation involving i - 1
. The most direct way to solve is by moving the decrease of i
towards 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 at 2
instead of the 1
, because otherwise you will eventually a % 1
which is always 0
(I mean, the show will say that every number is "Not prime").
Besides, there are two other "weird" things in your code:
Every 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.
Other than that, there is the use of break
- that maybe you haven’t learned yet. Spoiler: it serves to stop a loop earlier. If inside the if
you put an additional instruction - break;
- So now that he knows for sure that the number isn’t prime he doesn’t need to keep testing, he stops right there. There is also a way to stop earlier without using the break
:
while (i>2 && primo != 0){
That is, only continue if the i
is greater than 2
And the number is not proven to be non-prime.
Note: I learned C a million years ago at the time that neither
bool
had, so I gave my answer using0
to represent "false" and1
to represent "true". How do not know what you you know (since you are still learning) I preferred to make the example simpler - introducing the minimum of new concepts.– mgibsonbr