Розбір
Exponentiation is a mathematical operation, written as , involving two numbers, the base and the exponent or power . When is a positive integer, exponentiation corresponds to repeated multiplication of the base: that is, is the product of multiplying bases: .
How can we compute for given and ? One option is to use one loop with a time complexity of . The linear time algorithm will pass the time limit because .
Alternatively, you can use fast exponentiation:
Algorithm realization
Let's use the -bit integer type long long. Read the input data.
scanf("%lld %lld %lld",&x,&n,&m);
Compute the value of using a loop.
res = 1; for(i = 1; i <= n; i++) res = (res * x) % m;
Print the answer.
printf("%lld\n",res);
Algorithm realization — Fast Exponentiation
The PowMod function finds the value of .
long long PowMod(long long x, long long n, long long m) { if (n == 0) return 1; if (n % 2 == 0) return PowMod((x * x) % m, n / 2, m); return (x * PowMod(x, n - 1, m)) % m; }
The main part of the program. Read the input data.
scanf("%lld %lld %lld",&x,&n,&m);
Compute and print the answer.
res = PowMod(x,n,m); printf("%lld\n",res);
Java realization — linear complexity
import java.util.*; public class Main { public static void main(String[] args) { Scanner con = new Scanner(System.in); long x = con.nextLong(), n = con.nextLong(), m = con.nextLong(); long res = 1; for(int i = 1; i <= n; i++) res = (res * x) % m; System.out.println(res); con.close(); } }
Java realization — O(log2n)
import java.util.*; public class Main { static long PowMod(long x, long n, long m) { if (n == 0) return 1; if (n % 2 == 0) return PowMod((x * x) % m, n / 2, m); return (x * PowMod(x, n - 1, m)) % m; } public static void main(String[] args) { Scanner con = new Scanner(System.in); long x = con.nextLong(); long n = con.nextLong(); long m = con.nextLong(); long res = PowMod(x,n,m); System.out.println(res); con.close(); } }
Java realization — powMod
import java.util.*; import java.math.*; public class Main { public static void main(String[] args) { Scanner con = new Scanner(System.in); BigInteger x = con.nextBigInteger(); BigInteger n = con.nextBigInteger(); BigInteger m = con.nextBigInteger(); System.out.println(x.modPow(n,m)); con.close(); } }
Python realization — pow
Read the input data.
x, n, m = map(int, input().split())
Compute and print the answer. Use the built-in function pow to evaluate the expression .
print(pow(x, n, m))
Python realization — loop
Read the input data.
x, n, m = map(int, input().split())
Compute the value of using a loop.
res = 1 for i in range(1, n + 1): res = (res * x) % m
Print the answer.
print(res)