2
$\begingroup$

I was solving this equation: $$\text{key}=\left(\sum_{K=0}^n\frac{1}{a^K}\right)\bmod{m}.$$

Given

$$ 1,000,000,000 < a, n, m \; < 5,000,000,000, $$ $$ a, m \text{ are coprime}. $$

I solved it by brute force, but it won't work in the given constrains so I need a faster algorithm or is there is something I can notice to make the formula easier to solve ?

$\endgroup$

1 Answer 1

6
$\begingroup$

Solve a linear homogeneous recurrence to obtain the identity $$\sum_{K=0}^n\frac1{a^K}=\begin{cases}\frac{1-1/a^{n+1}}{1-1/a}&\text{if }a\neq1\pmod m\\n+1&\text{if }a=1\pmod m\end{cases}$$ and use efficient algorithms for multiplicative inversion and exponentiation mod $m$.

$\endgroup$
2
  • $\begingroup$ I can't recurrence through N .. It's at least 1,000,000,000 Or do you mean something else .. I've solved it already using this using the following recurrences $ S(2k)=S(k)(1+q^k)$ and $ S(2k+1)=q S(2k) +1$ where $ q = ModularMultiplicativeInverse( a ) $ and Got Accepted :) $\endgroup$ Commented Aug 22, 2012 at 3:58
  • 2
    $\begingroup$ You do not need to recurse, your formula (without mod) is just a sum of a geometric series and has a solution in a closed form as shown in the answer. Then you have to carry out all operations mod m. $\endgroup$
    – A.Schulz
    Commented Aug 22, 2012 at 6:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.