#include<iostream> #include<cstdio> usingnamespacestd; longlong b, p, k; longlongquick_pow(longlong base, longlongexp, longlong mod) { if (mod == 1) //任何数模1都等于0 return0; if (exp == 0) //任何非零常数的0次方都等于1 return1; longlong ans = 1; while (exp) { if (exp & 1) //如果末尾为1,则需要乘上该位的指数 { ans *= base; ans %= mod; //每步必模 } base = base * base; base %= mod; exp >>= 1; } return ans; } intmain() { scanf("%lld %lld %lld", &b, &p, &k); printf("%lld^%lld mod %lld=%lld", b, p, k, quick_pow(b, p, k)); return0; }
最大公约数(GCD)
要求 a,b 的最大公约数,可使用欧几里得辗转相除法。时间复杂度为 O(logn)
解决方案
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include<iostream> #include<cstdio> usingnamespacestd; longlonggcd(longlong a, longlong b) { if (a % b) return gcd(b, a % b); else return b; } intmain() { longlong a, b; scanf("%lld %lld", &a, &b); printf("%lld", gcd(a, b)); return0; }