Cod sursa(job #1511009)

Utilizator catu_bogdan_99Catu Bogdan catu_bogdan_99 Data 25 octombrie 2015 21:45:52
Problema Invers modular Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.97 kb
#include <cstdio>
using namespace std;


bool prim( int n ){

    int i;
    if( n <= 1 ) return false;
    for( i = 2; i * i <= n; ++i )
        if( n % i == 0 ) return false;

    return true;

}

int indi( int n ){


    int i, j, t;
    j = 1;

    if( prim(n) ) return n - 1;
    i = 2;

    while( n > 1 ){
        t = 1;
        while( n % i == 0 ){
            n /= i;
            t *= i;
        }
        if( t > 1 ) j *= ( i - 1 ) * ( t / i );
        i++;
    }

    return j;

}


int rid( long long x, long long n, int c ){
	int p = 1;
	x = x % c;

	while ( n > 0 ){
		if( n & 1 ){
			p = p * x % c;
			n--;
		}
		x = x * x % c;
		n >>= 1 ;
	}

	return p%c;
}


int main()
{

    freopen("inversmodular.in","r",stdin);
    freopen("inversmodular.out","w",stdout);

    int a, n, q;

    scanf("%d%d",&a,&n);

    q = indi( n ) - 1;
    //printf("%d\n",q);
    printf("%d",rid( a, q, n ));

    return 0;
}