I was taking a look at the following C Program exercise I found online which is an example on how to check for prime numbers using a recursive method, but when I tried it on my Visual Studios 2019 compiler, I found that certain numbers will simply cause a "Stack Overflow" error.
The exercise requires recursion instead of loops which is why I'm facing a stack overflow.
//c program to check whether a number is prime or not using recursive function
#include<stdio.h>
#include <stdlib.h>
int is_prime_number(int num, int i) //Function Definition
{
if(num < 2)
{
printf("\n Enter numbers greater than 1");
exit(0);
}
if (i == 1)
{
return 1;
}
else
{
if (num % i == 0)
{
return 0;
}
else
{
return is_prime_number(num, i-1);
}
}
}
//Driver Code
int main()
{
int n, flag; //Declare the variables
printf("Enter a number: \n"); // Ask the user for an input
scanf("%d",&n);
flag = is_prime_number(n, n / 2); //Function Call
if (flag == 1) //Print whether prime or not
{
printf("%d is a prime number\n", n);
}
else
{
printf("%d is not a prime number\n", n);
}
return 0;
}
For example a number like 77 or 120 will come back as not prime numbers, and numbers like 11 and 127 come back as prime numbers; however, when using big numbers like 23479823 a "Stack Overflow" error occurs and the program freezes. I also tried an even bigger number within INT_MAX of 2147483646 and it successfully came back as not prime.
Would greatly appreciate any clues on why this is occurring!