0

I need to find the value of

$$ n(n+1)/2 \pmod m $$

Note: $n \leq 10^{18}$ So intermediate calculations may overflow (I'm using a 64 bit data type to store n)

If m is odd, I can simply find x in $ 2^{-1} \equiv x \pmod m $ and multiply that to $ (n \mod m) * ((n+1) \mod m) $

But what if m is even? The multiplicative inverse won't exist. How do I calculate it then?

n*(n+1) is always an even integer, and if m is even, $ n(n+1) \mod m $ will also be even. So will just dividing by 2 give me the correct answer?

1 Answers1

1

You should condition on the parity of $n$, not $m$.

If $n = 2k$ is even, then $n(n+1)/2 = k(2k+1)$. Compute $k \mod m$. Call the result $r$. Then the answer is $r(2r+1) \mod m$.

If $n = 2k-1$ is odd, then $n(n+1)/2 = k(2k-1)$. Compute $k \mod m$. Call the result $r$. Then the answer is $r(2r-1) \mod m$.

Hans Engler
  • 15,439
  • I was considering parity of m because I need to find out inverse(2) mod m. If m is odd, the inverse will always exist, so there's no problem – Rushil Paul Feb 07 '15 at 20:13
  • With the solution I just gave you, you don't have to compute that inverse. – Hans Engler Feb 07 '15 at 20:14
  • @Rushil Modular fractions are not well-defined if the denominator is not coprime to the modules, e.g. see here. – Bill Dubuque Feb 07 '15 at 20:16
  • @BillDubuque Yes I know, that's why I was wondering what to do if the inverse won't exist. – Rushil Paul Feb 07 '15 at 20:19
  • @Rushil Does your expression mean take the integer $, k := n(n+2)/2,$ then reduce it mod $m,,$ or does it instead denote the solution(s) of $, 2x\equiv n(n+1)\pmod m?,$ The latter will have $2$ solutions when $,m,$ is even, e.g. $,2x\equiv 6\pmod{10}\iff x\equiv 3\pmod 5\iff x\equiv 3,8\pmod{10}\ $ when $\ m=10,\ n = 2\ $ so the "fraction" $,x = 6/2,$ is not well-defined mod $,10.\ \ $ – Bill Dubuque Feb 07 '15 at 20:24
  • @BillDubuque My expression is the former one. – Rushil Paul Feb 07 '15 at 20:30
  • @Rushil Then the description in the question is incorrect since the quotient operation denotes an operation on integers (not modular integers). – Bill Dubuque Feb 07 '15 at 21:05
  • n(n+1)/2 is an integer. I want to take that integer mod m. I don't quite understand what is wrong with that – Rushil Paul Feb 07 '15 at 21:13
  • @Rushil The point is that your question talks about computing modular inverses of $2$ etc, bit these never occur if the quotient denotes a quotient of integers. What you wrote in the question makes it seem like the denotation is actually the latter one I mentioned above, where the quitient (or fraction) is a modular one. – Bill Dubuque Feb 07 '15 at 21:19
  • @Rushil - while $n(n+1)/2$ is indeed an integer, it is not a good idea to compute $n(n+1)/2 % m$ as $(n % m) \cdot ((n+1) % m) \cdot (2^{-1} % m)$ as you have attempted to do. It can lead to errors or to confusion (as in this case). – Hans Engler Feb 07 '15 at 22:25
  • @HansEngler Yes I realize that now – Rushil Paul Feb 07 '15 at 22:28