All problems

Problem 240

Modular Inverse

Medium · 20 pts · Math, Number Theory

Problem

You are given an integer A. Find the integer X between 0 and 1000000006 such that A × X leaves remainder 1 when divided by 1000000007 (a prime number). This X is called the modular inverse of A. If no such X exists, print -1. That happens exactly when A is a multiple of 1000000007 (including A = 0). First reduce A modulo p = 1000000007. Then, by Fermat's little theorem, the inverse is A^(p - 2) mod p, computed with fast exponentiation. The extended Euclidean algorithm also works. The numbers in this problem can be larger than a 32-bit int can hold (about 2.1 × 10^9), so use a 64-bit integer type: long long in C++, long in Java (Python needs nothing special).

Input

A single integer A.

Output

Print the modular inverse of A, or -1.

Constraints

0 <= A <= 10^18

Example input

2

Example output

500000004

Explanation

2 × 500000004 = 1000000008, which is 1 more than 1000000007, so it leaves remainder 1. The modular inverse of 2 is therefore 500000004.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Nth Ugly Number Next: Count Primes in a Range