So this is the code and it works perfectly fine till 4-5 digits.
int main()
{
int x;
printf("Enter a number: ");
scanf("%d", &x);
double list[x];
int i;
for(i=0;i<x;i ){
list[ i ] = i 1;
}
double z;
int q;
double list2[x];
for(q=0;q<x;q ){
z=x/list[q];
if (z == floor(z)){
list2[q] = z;
}
else {
list2[q] = 0;
}
}
printf("\n--------------\n");
int n;
double nulla = 0.00000000;
int zero = 0;
for(n = 0; n < x; n )
{
if (fabs(list2[n]-0.00)==0.00){
zero ;
}
}
if(zero == x-2){
printf("It is a prime number");
}
else{
printf("It is not a prime number");
}
printf("\n--------------\n");
return 0;
}
But if i input for example 987521. It just gives this message: Process returned -1073741571 (0xC00000FD)
and I have been thinking that maybe an array cannot store such a large data, but maybe i am wrong. Any thoughts?
CodePudding user response:
Instead of allocating memory on the stack, as you do in the line
double list[x];
use dynamic allocation, like
double* list = malloc(x * sizeof(double));
Then, before the end of the program, don't forget to deallocate:
free(list);
The reason is that stack allocation is usually quite limited in size (order of MBs), and you'll overflow the stack once you allocate more than that limit. On the other had, dynamic memory (heap) is limited by the operating system, and can usually be quite large (limited by either the OS or the amount of total physical virtual memory).