Reputation: 77
I was trying to solve a problem( http://www.codechef.com/BTCD2012/problems/DOORS) on an online judge. Following is the code for the problem.When i submit the judge gives runtime error(other).Am i using too much memory,if it is so then please help me out in finding other way,because memory has been used according to given constraints.
The constraint are as follow:
0< t1 <1000000;
0< num<100000000;
#include<stdio.h>
int a[100000001];
int main()
{
int t=3,j,k1,g,k=1,m,n=0,i,t1,num;
for(i=1;i<10000;i++)
{
m=i*i;
n=n+t;
for(j=m;j<=n;j++)
{
a[j]=k;
}
k++;
t=t+2;
// printf("a[%d]--> %d\n",n,a[n]);
}
scanf("%d",&t1);
for(k1=0;k1<t1;k1++)
{
scanf("%d",&num);
printf("%d\n",a[num]);
}
getch();
// return 0;
}
Upvotes: 2
Views: 9799
Reputation: 1
try this algo..: Try to find out how many perfect squares between 1 and n.. prefect squares have odd number of multiples and i think that will be the ans.. suppose n=1000, there are only 31 perfect squares between 1 to 1000. so,the number of open doors after she leaves= 31.
Upvotes: 0
Reputation: 1990
The line:
int a[100000001];
Attempts to allocate 381.5 MB of memory on the stack. This is most likely too large for the runtime to handle, so the program is being terminated.
Do you really need that many ints?
If you do really need that much memory, try allocating it in the heap instead:
change the global to a pointer:
int *a;
at the start of main()
a = malloc(sizeof(int)*100000001);
if(!a)
{
printf("Could not allocate contiguous block\n");
return -1;
}
Upvotes: 1
Reputation: 5399
Hey first of all good question :-) "+1" for that.
Now to your question,
Always a good practice to dynamically allocate the memory if you are sure that you need this much of them. Try malloc
ing the variable a
. How many bytes is your int
using? And still better to use unsigned long long
if you are sure that you do not need any signed bits
.
unsigned int* a ;
a = malloc( sizeof(int) * 100000001 ) ;
The answers above and the comments are too very useful.
Upvotes: 0
Reputation: 2971
int a[100000001];
This line is the problem, its allocating too much memory in static allocation area! As suggested, you could use malloc() to allocate this memory on the heap.
A much leaner way would be to use an array of bits [each bit representing a door, you just need to turn them on and off to represent open or close status of the doors]. It will be bit tricky to implement but your program will be much leaner (at least 16 times, a C int is at least 2 bytes, 16 bits) and much faster!
Upvotes: 1