Now I’ve enough karma to start a new thread, so thank you people for upvotes.
I read the CHN08 - Editorial, and after that I came up this solution which works very fine. But I’m not able to understand why I have to add modular(10^7+1) to temp when temp<0. I’m talking about this line.
What the setter wanted to convey was, he always wants a positive answer. And since answer may be large, output the remainder with 10^9 +7. In case the number is negative, he did not want you to print the negative remainder, and hence you add 10^9+7 till number becomes positive and proceed.
Alternatively, always taking absolute values should also do fine according to me. 10^9+7 - [abs(f(n) )%10^9+7]
F(n) can be negative, but its of no conern. Theres a difference b/w what f(n) can be and what the setter wants us to print. Check his sample case, he made it clear there that if f(n) is negative, you need to print [f(n)%10^9+7]+10^9+7
Also, your approach, although correct, needs improvement. Since n (or in your program, x) can range from 1 to 10^9, its very easy to exhaust ‘recursion depth’. Infinite/too large recursion can give runtime error/SIGSEV error.