Cod sursa(job #2022447)

Utilizator gabib97Gabriel Boroghina gabib97 Data 16 septembrie 2017 16:06:45
Problema Invers modular Scor 100
Compilator java Status done
Runda Arhiva educationala Marime 1.5 kb
import java.util.*;
import java.io.*;

class Pair {
    long x, y;
}

public class Main {
    public static void im(long a, long b, Pair p) {
        if (b == 0) {
            p.x = 1;
            p.y = 0;
        } else {
            Pair p0 = new Pair();
            im(b, a % b, p0);

            p.x = p0.y;
            p.y = p0.x - (a / b) * p0.y;
        }
    }

    public static void main(String[] args) throws IOException {
        MyScanner cin = new MyScanner("inversmodular.in");
        PrintWriter cout = new PrintWriter("inversmodular.out");

        long a = cin.nextInt();
        long n = cin.nextInt();

        Pair p = new Pair();
        im(a, n, p);
        if (p.x < 0) p.x = n + p.x % n;

        cout.print(p.x);
        cout.close();
    }

    private static class MyScanner {
        private BufferedReader bufferedReader;
        private StringTokenizer stringTokenizer;

        MyScanner(String filename) throws FileNotFoundException {
            bufferedReader = new BufferedReader(new FileReader(filename));
        }

        private String next() throws IOException {
            while (stringTokenizer == null || !stringTokenizer.hasMoreElements()) {
                stringTokenizer = new StringTokenizer(bufferedReader.readLine());
            }
            return stringTokenizer.nextToken();
        }

        int nextInt() throws IOException {
            return Integer.parseInt(next());
        }

        void close() throws IOException {
            bufferedReader.close();
        }
    }
}