5

I am looking for a way to implement division in modular arithmetic using modulo prime.

The method I found in math books is to try $u$ such that

$au \equiv 1 \pmod{p}$

$b/a \equiv bu \pmod{p}$

where $a, b, u \in Z_p$ (remainder class modulo a prime $p$). But trying things is probably not a good and fast approach (as it seems to me it has linear complexity and my $p$ can be big, up to $10^9$). What is the right way to do division in modulo prime?

Thinh D. Nguyen
  • 2,275
  • 3
  • 23
  • 71
A123321
  • 237
  • 1
  • 2
  • 8

1 Answers1

10

To divide $b$ by $a$, you follow two steps: first you find $u$ such that $au \equiv 1 \pmod{p}$, and then you compute $bu \pmod{p}$. To find $u$, you run the extended GCD algorithm on $a$ and $p$. If it is indeed the case that $a \not\equiv 0 \pmod{p}$, then since $p$ is prime $(a,p) = 1$. So the GCD algorithm will come up with numbers $u,v$ such that $$ au + pv = 1. $$ In other words, $au \equiv 1 \pmod{p}$.

Yuval Filmus
  • 276,994
  • 27
  • 311
  • 503
  • When I want to divide $1/2 \pmod{3}$ then the result should be $2$ because $2 * u = 1 \pmod{3}$, so $u$ has to be $2$ (and then $b * u = 2$). However when I run extended GCD http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm#Formal_description_of_the_algorithm I get $u$ ($lastx$ on wiki) equal to $0$. I can't find out why it shouldn't be $0$ but it doesn't match equations for modular division above. Can you please explain? – A123321 Mar 19 '13 at 13:39
  • Sorry, that was just implementation problem. – A123321 Mar 19 '13 at 14:57