Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Basics

Modular Inverse

Medium · Basics · Asked at Google, Amazon, Codenation

Let p = 10^9 + 7 (a prime). For each query a, print the number x with 0 ≤ x < p such that (a × x) mod p = 1.

Input

First line: q. Next q lines: one integer a each.

Output

q lines — the inverse of each a modulo 10^9 + 7.

Constraints

Fermat's little theorem: a^(p−1) ≡ 1 (mod p), so a^(p−2) is the inverse. Compute it with fast exponentiation in O(log p).

Example 1

Input

3
2
3
1

Output

500000004
333333336
1

Hints

  1. p is prime, so Fermat's little theorem applies: a^(p−1) ≡ 1 (mod p).
  2. Then a × a^(p−2) ≡ 1 — the inverse is a^(p−2) mod p.
  3. Compute the power with fast (binary) exponentiation.

Approach

Fast exponentiation squares the base and halves the exponent each step, multiplying the base into the answer whenever the current bit of the exponent is 1. Every multiplication is taken mod p, so with 64-bit integers nothing overflows (both factors are below 2^30). Each query costs about 30 steps.

Complexity: O(q · log p) time · O(1) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

const long long MOD = 1000000007LL;

long long power(long long b, long long e) {
    long long res = 1;
    b %= MOD;
    while (e > 0) {
        if (e & 1) res = res * b % MOD;
        b = b * b % MOD;
        e >>= 1;
    }
    return res;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int q;
    cin >> q;
    while (q--) {
        long long a;
        cin >> a;
        cout << power(a, MOD - 2) << "\n";
    }
    return 0;
}

Python solution

import sys

MOD = 10**9 + 7
data = sys.stdin.read().split()
q = int(data[0])
print("\n".join(str(pow(int(a), MOD - 2, MOD)) for a in data[1 : 1 + q]))

Java solution

import java.io.*;

public class Main {
    static final long MOD = 1000000007L;

    static long power(long b, long e) {
        long res = 1;
        b %= MOD;
        while (e > 0) {
            if ((e & 1) == 1) res = res * b % MOD;
            b = b * b % MOD;
            e >>= 1;
        }
        return res;
    }

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int q = Integer.parseInt(br.readLine().trim());
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < q; i++) sb.append(power(Long.parseLong(br.readLine().trim()), MOD - 2)).append('\n');
        System.out.print(sb);
    }
}

Solve Modular Inverse online · All practice problems