Cod sursa(job #1799093)

Utilizator msciSergiu Marin msci Data 5 noiembrie 2016 19:09:23
Problema Ridicare la putere in timp logaritmic Scor 0
Compilator java Status done
Runda Arhiva educationala Marime 2.16 kb
/* Exponentiation by Squaring algorithm
 * Running Time = O(log n)
 */
package sergiu.algorithms;

import java.util.*;
import java.io.*;

public class ExpbySq {
    FastScanner in;
    PrintWriter out;

    void solve() {
        long x = in.nextLong();
        long n = in.nextLong();

        out.println((exp(x, n) % 1999999973));
    }

    long exp(long x, long n) {
        if (n == 0) return 1;
        else if (n == 1) return x;
        else if (n % 2 == 0) return exp(x * x, n / 2);
        else return x * exp(x * x, (n - 1) / 2);
    }

    void run() {
        try {
            in = new FastScanner(new File("lgput.in"));
            out = new PrintWriter(new File("lgput.out"));

            solve();

            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    void runIO() {
        in = new FastScanner(System.in);
        out = new PrintWriter(System.out);

        solve();

        out.close();
    }

    class FastScanner {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public FastScanner(File f) {
            try {
                reader = new BufferedReader(new FileReader(f));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }

        public FastScanner(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return tokenizer.nextToken();
        }

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

        public double nextDouble() {
            return Double.parseDouble(next());
        }

        public long nextLong() {
            return Long.parseLong(next());
        }
    }

    public static void main(String[] args) {
        new ExpbySq().run();
    }
}