PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#SP0000277. Khôi phục khóa bí mật RSA (Cracking RSA)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Khôi phục khóa bí mật RSA (Cracking RSA)

Cracking RSA

Source: Kattis

Version: Phuoc Hung OJ Extended

Problem Statement

An RSA public key is a pair (n,e)(n,e). The integer nn is the product of two distinct primes pp and qq: n=pqn=pq. Define φ(n)=(p−1)(q−1)\varphi(n)=(p-1)(q-1). The private exponent dd satisfies de≡1(modφ(n))de\equiv1\pmod{\varphi(n)} and 1<d<φ(n)1<d<\varphi(n). Given the public key (n,e)(n,e), find its private exponent dd. The input guarantees that a unique valid dd exists.

Input

One line contains integers nn and ee, separated by a space. The number nn is the product of two distinct primes pp and qq.

Output

Print the integer dd, the required private exponent.

Subtasks

  • Subtask 1 (20 points): n=pqn=pq for distinct primes p,qp,q; 2≤p,q<302\le p,q<30; 1<e,d<(p−1)(q−1)1<e,d<(p-1)(q-1); ed≡1(mod(p−1)(q−1))ed\equiv1\pmod{(p-1)(q-1)}.
  • Subtask 2 (30 points): n=pqn=pq for distinct primes p,qp,q; 2≤p,q<2002\le p,q<200; 1<e,d<(p−1)(q−1)1<e,d<(p-1)(q-1); ed≡1(mod(p−1)(q−1))ed\equiv1\pmod{(p-1)(q-1)}.
  • Subtask 3 (50 points): n=pqn=pq for distinct primes p,qp,q; 2≤p,q<10002\le p,q<1000; 1<e,d<(p−1)(q−1)1<e,d<(p-1)(q-1); ed≡1(mod(p−1)(q−1))ed\equiv1\pmod{(p-1)(q-1)}.

Examples

Example 1

Input

33 3

Output

7

Explanation

Here n=33=3⋅11n=33=3\cdot11, so p=3p=3, q=11q=11 and φ(n)=(3−1)(11−1)=20\varphi(n)=(3-1)(11-1)=20. The private exponent satisfies 3d≡1(mod20)3d\equiv1\pmod{20}. Since 3⋅7=21=1⋅20+13\cdot7=21=1\cdot20+1, the required exponent is d=7d=7, and the output is 7.

Example 2

Input

65 11

Output

35

Explanation

Here n=65=5⋅13n=65=5\cdot13, so p=5p=5, q=13q=13 and φ(n)=(5−1)(13−1)=48\varphi(n)=(5-1)(13-1)=48. We require 11d≡1(mod48)11d\equiv1\pmod{48}. Since 11⋅35=385=8⋅48+111\cdot35=385=8\cdot48+1, the required private exponent is d=35d=35, and the output is 35.