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