#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define mod 1000000007
int main()
{
unsigned long long int n,i,j,k;
unsigned long long int *power = (unsigned long long int *)malloc(sizeof(unsigned long long int) * (1000000000LL));
power[0] = 1;
for(i = 1;i <= 1000000000LL;i++){
power[i] = (power[i-1] * 2 ) % mod;
}
int t;
scanf("%d",&t);
while(t--){
scanf("%lld",&n);
unsigned long long int f = 2;
for(i=2; i<=n;i++){
f = (f + power[i/2]) % mod;
}
printf("%llu\n",f);
}
return 0;
}
Asked
Active
Viewed 183 times
0

Daniel Fischer
- 181,706
- 17
- 308
- 431
-
1When `malloc` is unable to allocate the memory for you, it may return a null pointer. Dereferencing one would cause undefined behaviour. You should always check the return value before using is. – eq- Sep 03 '12 at 14:25
-
There's no need for the `LL`. An integral literal always has a type in which it fits, if such a type exists. – Kerrek SB Sep 03 '12 at 14:29
-
@KerrekSB I believe that's a pretty recent behavior though, else why do we have the type suffixes? – unwind Sep 03 '12 at 14:39
-
@unwind: Well, you can say `printf("%lu", 1UL)`, but you cannot say `printf("%lu", 1)`... – Kerrek SB Sep 03 '12 at 14:42
-
[Do not cast the return of malloc](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Eregrith Sep 03 '12 at 14:42
-
@unwind If you call 13 years recent, then yes. – Daniel Fischer Sep 03 '12 at 16:37
-
Does your computer even have 8GB of ram? – Mysticial Sep 03 '12 at 16:57
-
Welcome to StackOverflow. Please provide a simple explanation of what you're trying to achieve with your code. Also, try reducing your code to an [SSCCE](http://sscce.org/) - often you will discover the problem during this process. See the [FAQ](http://meta.stackexchange.com/questions/7931/faq-for-stack-exchange-sites) for more details. – Joseph Mansfield Sep 27 '12 at 11:46
4 Answers
6
Surely power[1000000000]
is out of bounds! Your array doesn't have that many elements. You need <
, not <=
in the loop.

Kerrek SB
- 464,522
- 92
- 875
- 1,084
2
Because you did not test the return value of malloc. It fails by giving NULL (e.g. when out of memory).

Basile Starynkevitch
- 223,805
- 18
- 296
- 547
0
This is not a good idea
for(i = 1;i <= 1000000000LL;i++){
indices are zero based anyway but you should replace the <=
with a <
to prevent from reading past the end of the array
Also given the size of the array you are trying to allocate you should check your power
pointer is valid.

mathematician1975
- 21,161
- 6
- 59
- 101