Calculating sum of geometric series (mod m)

前端 未结 4 737
难免孤独
难免孤独 2020-12-14 02:43

I have a series

S = i^(m) + i^(2m) + ...............  + i^(km)  (mod m)   

0 <= i < m, k may be very large (up to 100,000,000),  m <= 300000
         


        
4条回答
  •  时光取名叫无心
    2020-12-14 03:26

    This is the algorithm for a similar problem I encountered

    You probably know that one can calculate the power of a number in logarithmic time. You can also do so for calculating the sum of the geometric series. Since it holds that

    1 + a + a^2 + ... + a^(2*n+1) = (1 + a) * (1 + (a^2) + (a^2)^2 + ... + (a^2)^n),
    

    you can recursively calculate the geometric series on the right hand to get the result.

    This way you do not need division, so you can take the remainder of the sum (and of intermediate results) modulo any number you want.

提交回复
热议问题