Problems to calculate the largest prime int in C

Asked

Viewed 219 times

0

Hello.

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

Follows 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;
}

1 answer

0


In function main() flames 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 at all times less than or equal to INT_MAX.

Tip: start checking in 2 (instead of 0) and goes to the square root of n. If you catch a divider, just return it 0 without calculating other dividers.

  • I did it! Thank you very much. I did the algorithm testing only up to the square root, and a loop out of the function testing first the INT_MAX and decreasing until finding the first prime.

Browser other questions tagged

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