Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Super Pow in C++
Suppose we have to calculate a^b mod 1337 where a is one positive integer and b is an extremely large positive integer given in the form of an array. So if a = 2 and b = [1,0] then the output will be 1024
To solve this, we will follow these steps −
Define powerMod() method this takes base and power
m := 1337, ret := 1
-
while power is not 0
if power is odd, then ret := ret * base mod m
base := base^2 mod m
power := power / 2
return ret
Define superPower(), this takes a and b
if size of b = 0, then return 1
last := last element of b
delete last element from b
return powerMod(superpower(a, b), 10) * powerMod(a, last)) mod 1337
Example(C++)
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
class Solution {
public:
int powerMod(lli base, lli power){
lli mod = 1337;
lli ret = 1;
while(power){
if(power & 1) ret = (ret * base) % mod;
base = (base * base) % mod;
power >>= 1;
}
return ret;
}
int superPow(int a, vector<int>& b) {
if(b.size() == 0) return 1;
int last = b.back();
b.pop_back();
return (powerMod(superPow(a, b), 10) * powerMod(a, last)) % 1337;
}
};
main(){
Solution ob;
vector<int> v = {1,0};
cout << (ob.superPow(2, v));
}
Input
2 [1,0]
Output
1024
Advertisements