Cod sursa(job #2891312)

Utilizator Stefanstef99Stefan Puica Stefanstef99 Data 18 aprilie 2022 09:48:31
Problema Ridicare la putere in timp logaritmic Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.08 kb
#include <bits/stdc++.h>
#define MOD 1999999973
using namespace std;

/**
Se dau a>1 si P>1. Să se determine un numar natural b
a.i. a * b % P = 1.

Ex: a=5, P=17 => b = 7
5*7 % 17 = 35 % 17 = 1

b se numeste invers modular al lui a in raport cu P.

In general noi avem de calculat un raport
x/y % P

n! / (n-k)! % P
n! / (n-k)! = (n-k+1)*(n-k+2)* ... * n % P

1) (a + b) % P = (a % P + b % P) % P
ex: (10 + 20) % 7 = 2
    (10 % 7 + 20 % 7) % 7 = (3+6) % 7 = 2
2) (a * b) % P = ((a % P) * (b % P)) % P
3) (a - b) % P = (a % P - b % P + P) % P

4) a/b % P = a * c % P, unde c este inversul modular al lui b

ex: 35 / 5 % 17 = 35 * 7 % 17 = 7
*/

long long QuickExpo(long long a, long long P)
{
    long long rez = 1;
    while (P > 0)
    {
        if (P % 2 == 1) rez = rez * a % MOD;
        P /= 2;
        a = a * a % MOD;
    }
    return rez;
}

int main()
{
    long long a, n;
    ifstream fin("lgput.in");
    ofstream fout("lgput.out");
    fin >> a >> n;
    fout << QuickExpo(a, n) << "\n";
    fout.close();
    fin.close();
    return 0;
}