Let mod be $$$10^9 + 9$$$. I want to calculate X % mod where $$$ X = ((a/b)^ n -1 )/(a/b - 1)$$$. I know inverse modulo of number N with respect to mod is $$$N^{mod-2}$$$. Also $$$n$$$ is very large so I cannot iterate and add the sum by each term ( I cannot sum the terms $$$1 + (a/b)^1 + (a/b)^2 .. (a/b)^{n-1} $$$). Please help, I was trying to solve this problem. 963A - Alternating Sum
What's the issue?? Handle the case where a = b separately and note that 10^9+9 is prime number so write (a/b) as a*b^(-1) modulo N, N = 10^9+9....Where are you facing problem??
You can apply the same technique that is used for binary exponentiation.
Even case: $$$a^0 + a^1 + \ldots + a^{2k - 1} = (a^0 + a^k) \cdot (a^0 + a^1 + \ldots + a^{k - 1})$$$
Odd case: $$$a^0 + a^1 + \ldots + a^{2k - 1} + a^{2k} = (a^0 + a^k) \cdot (a^0 + a^1 + \ldots + a^{k - 1}) \cdot a + 1$$$, where the last $$$1$$$ is just $$$a^0$$$.
In both cases, we reduce finding the sum until $$$2k$$$ or $$$2k + 1$$$ to finding the sum until $$$k$$$.
Can I write $$$X \% mod = ( (t \% mod)^n - 1 ) \% mod * (INVERSE(t - 1 , mod-2) \% mod) ) \% mod $$$ , where $$$ t = ( (a \% mod) * ( INVERSE(b, mod-2) \% mod) ) \% mod $$$ ?
Of course you can write all you want, but to make it work as expected, you better understand it.
In the current version,
inverse
with amod - 2
argument looks suspicious. You may have apowMod (value, power[, mod])
. You may also have ainverse (value[, mod])
which might be a shorthand forpowMod (value, mod - 2[, mod])
. Do figure out what thatmod - 2
means there before proceeding.[deleted] a,b are less than $$$10^9$$$. I will try the Binary Exponentiation method you mentioned.