Problems to calculate the largest int prime in C

0

Hello.

I'm trying to calculate the largest prime number that fits into an int variable. My idea was to start with the biggest int, and go check in descending order until you find the first prime number. When I try to run the program I get the message: "mayorprimo.exe has stopped working. Windows is verifying a solution to the problem."

Follow the code:

#include <stdio.h>
#include <limits.h>

int main(){
    int primo=0;
    int num=INT_MAX;
    for(num; num>0; num--){
        primo=ePrimo(num);
        if(primo==1){
            printf("%d eh primo" ,num);
            break;
        }
    }
}

int ePrimo(int n){
    int i;
    int cont;
    for(i=0; i<=n; i++){
        if(n%i==0){
            cont++;
        }
    }
    if(cont==2)
        return 1;
    else
        return 0;
}
    
asked by anonymous 28.02.2016 / 14:11

1 answer

0

In function main() you call the function ePrimo() with the value INT_MAX .

In function ePrimo() your cycle

for (i = 0; i <= n; i++) { /* ... */ }

is an infinite cycle.

i is always less than or equal to INT_MAX .

Tip: start checking on 2 (instead of 0 ) and goes to the square root of n . If you get a divider, it returns 0 without calculating other divisors.

    
28.02.2016 / 14:22