After compiling and running, the algorithm shows "recorded excess floating point", why?

Asked

Viewed 66 times

1

Algorithm to find out if a number is prime, giving the floating point excess error.

#include<stdio.h>

int main(){

int n, i, divisivel;
divisivel =0;

printf("Digite um numero para saber se eh primo: \n");
scanf("%d", &n);

for(i = n; i >= 0; i--){
        if(n%i == 0){
            divisivel =divisivel + 1;
        }


}

if(divisivel <=2){
    printf("o numero %i eh primo!: \n", n);

}else{
    printf("o numero %i não eh primo \n", n);
}
return (0);
}
  • 1

    Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site

1 answer

2

The mistake there is that it is dividing by 0 since the condition of the for let it go to 0, then you should only compare if it is greater than zero and not equal. Actually there is no reason to buy if the division by 1 works, all numbers give. Simplifying the code would be like this:

#include<stdio.h>

int main() {
    int n;
    printf("Digite um numero para saber se eh primo: \n");
    scanf("%d", &n);
    int divisivel = 0;
    for (int i = n; i > 1; i--) {
        if (n % i == 0) {
            divisivel++;
            if (divisivel == 2) {
                printf("o numero %i não eh primo \n", n);
                return 0;
            }
        }
    }
    printf("o numero %i eh primo \n", n);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

In fact the code can be optimized using square root, search on this..

  • Thanks, man, you helped me a lot. I’m learning how to program now, so there’s a lot of details I don’t know yet. Thank you very much

  • @mitobk6 see on [tour/ the best way to say thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.