Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am trying to find primes $p$ and $q$ in the RSA algorithm given $n = pq$ and the value of $\phi(n)$. I know the following:

  1. $\phi(n) = (p-1)(q-1) = pq - p - q + 1$
  2. Solving for $p+q = pq - \phi(n) + 1$
  3. Take $(p-q)^2 = p^2 - 2pq + q^2$
  4. Solve $(p-q) = \sqrt{p^2 -2pq + q^2}$
  5. Simplify to $(p-q) = \sqrt{p^2 + 2pq -4pq + q^2} = \sqrt{(p+q)^2 -4pq}$

Now we can solve for $p$ and $q$:

$p = \dfrac{(p+q) +(p-q)}{2}$ and $q = \dfrac{(p+q)-(p-q)}{2}$

Is there a better or faster way to solve for $p$ and $q$ given $pq$ and $\phi(pq)$

share|cite|improve this question
Did you see this posting?… – Amzoti Sep 24 '12 at 2:29
up vote 7 down vote accepted

There is, based on the simple fact that $$(X-p)(X-q)=X^2-2\frac{p+q}{2}X+pq.$$

All you need to do is compute $\displaystyle m=\frac{p+q}{2}=\frac{n-\phi(n)+1}{2}$, then $$p,q=m\pm\sqrt{m^2-n}.$$

share|cite|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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