- #1
Saitama
- 4,243
- 93
Hello again everyone! :)
I have been trying to implement K^(2^N) mod 10^9+7 in C++ where both K and N are integers and $1\le K\le 10^5$ and $1\le N\le 10^9$.
My idea is to use the fact that
$$a_n=K^{2^N}=K^{2^{N-1}}\cdot K^{2^{N-1}}=a_{n-1}^2$$
Following is the code I wrote:
But it fails to work for $K=10^5$ and $N=10^6$. So I suppose I need to find another way to solve the problem. I am out of ideas.
Any help is appreciated. Many thanks!
I have been trying to implement K^(2^N) mod 10^9+7 in C++ where both K and N are integers and $1\le K\le 10^5$ and $1\le N\le 10^9$.
My idea is to use the fact that
$$a_n=K^{2^N}=K^{2^{N-1}}\cdot K^{2^{N-1}}=a_{n-1}^2$$
Following is the code I wrote:
Code:
#include<iostream>
#define modulo 1000000007
using namespace std;
typedef unsigned long long ull;
int K;
ull power(int N)
{
if(N==0)
return K;
ull x=power(N-1)%modulo;
ull ans=(x*x)%modulo;
return ans;
}
int main()
{
int T, N;
cin>>T;
while(T--)
{
cin>>K>>N;
cout<<power(N)<<endl;
}
return 0;
}
But it fails to work for $K=10^5$ and $N=10^6$. So I suppose I need to find another way to solve the problem. I am out of ideas.
Any help is appreciated. Many thanks!
Last edited: