Your task is to efficiently calculate values modulo
Example:
Input: a = 3, b = 7, c = 1
Output: 2187
Approach
Java
public class ExponentiationII {public static void main(String[] args) {long a = 3, b = 7, c = 1;exponentiationII(a, b, c);}static long MOD = (long) (1e9 + 7);static long power(long a, long b, long m) {long res = 1;while (b > 0) {if (b % 2 == 1)res = res * a % m;a = a * a % m;b /= 2;}return res;}static void exponentiationII(long a, long b, long c) {System.out.println(power(a, power(b, c, MOD - 1), MOD));}}
C++
#include <bits/stdc++.h>using namespace std;const long long MOD = 1e9 + 7;long long power(long long a, long long b, long long m){long long res = 1;while (b){if (b % 2)res = res * a % m;a = a * a % m;b /= 2;}return res;}void exponentiationII(long long a, long long b, long long c){cout << power(a, power(b, c, MOD - 1), MOD) << "\n";}int main(){long long a = 3, b = 7, c = 1;exponentiationII(a, b, c);return 0;}
No comments:
Post a Comment