prathams's blog

By prathams, 9 years ago, In English

For two given integers n and k, How to find

(Zn + Zn - 1 - 2Zn - 2) mod 10000007,

where Zn = Sn + Pn and

Sn = 1k + 2k + 3k + ….. + nk and

Pn = 11 + 22 + 33 + …… + nn

Constraint : (1 < n < 2 * 108, 0 < k < 106)

I got this problem on link

  • Vote: I like it
  • +1
  • Vote: I do not like it

»
9 years ago, # |
  Vote: I like it +4 Vote: I do not like it

It's a simple math problem, i think.
If we write Zn = Sn + Pn = nk + Sn - 1 + nn + Pn - 1
So we can write Zn + Zn - 1 = nk + nn + 2 * Zn - 1
As a result, we can write Zn + Zn - 1 - 2 * Zn - 2 = nn + nk + 2 * (n - 1)n - 1 + 2 * (n - 1)k.
This can be calculated in logarithmic time with fast exponentiation.

»
9 years ago, # |
Rev. 6   Vote: I like it +1 Vote: I do not like it

I solved it with the following thought process (In my opinion, giving thoughts is more important than the solution itself).
First notice the coefficients Zn + Zn - 1 - 2Zn - 2)
1 + 1 - 2 = 0
That looks suspicious!

Then we take a look at Sn and Pn.
Hmm ... Have you noticed something interesting?
If not, write down S3 S4 S5 and so on
and you'll notice:
Sn = Sn - 1 + nk = Sn - 2 + (n - 1)k + nk
Similarly with Pn
Pn = Pn - 1 + nn = Pn - 2 + (n - 1)n - 1 + nn

Then we substitute Sn, Sn - 1, Pn, Pn - 1 in the original sequence,
we get Zn + Zn - 1 - 2Zn - 2 = 2(n - 1)k + nk + 2(n - 1)n - 1 + nn

which leads to the solution