I want to sum a GP with common diff = -1/3, first term = 3^(n-1) till last term = +3/-3(depends on n). I know I can use the pow function but i want the answer to be mod 10^9+7 as n can be very large (like-1000000). My main problem is that when I input n greater than approx 25 I start getting negative output (for ex. when n=30 --> output = -3007262). I also checked here and tried the code here but the answer again started to become negative for larger numbers. Can anyone tell me a good faster and precise way to do this? my code (bad, ik):
#include <iostream>
using namespace std ;
long long ipow(int p , int k ){
long long ans = 1;
for(int i = k ; i > 0;--i ){
ans *= p;
ans %= 1000000007;
}
return ans;
}
int main(){
long long ans =0;
int n;
cin >> n;
if(n%2 != 0){
for(int i = n-1; i >0 ; i-=2){
ans += ipow(3,i);
ans -= ipow(3,i-1);
}
cout<< ans%1000000007<<"\n" ;
}
else{
for(int i = n-1; i >0 ; i-=2){
ans += ipow(3,i);
ans -= ipow(3,i-1);
}
cout<< (ans+1)%1000000007<<"\n" ;
}
return 0 ;
}
ps : You can see above I also didn't use the direct formula for a sum of a GP because the common diff is -1/3 but I want the answer to be int and when converting the answer from double (output is in double when pow function is used with input as -1/3) to int does not give me the precise int in many cases.