- #1
Saitama
- 4,243
- 93
I am trying this problem on CodeChef: Just a simple sum
My task is to evaluate:
$$\sum_{i=1}^n i^i \pmod m$$
Following is the code I have written:
But this code exceeds the time limit.
How do I optimise it?
Thanks!
My task is to evaluate:
$$\sum_{i=1}^n i^i \pmod m$$
Following is the code I have written:
Code:
#include <iostream>
using namespace std;
typedef long long ll;
ll modularPower(ll base, ll exponent, ll M)
{
ll res = 1;
while (exponent)
{
if (exponent & 1)
res = (res * base) % M;
exponent >>= 1;
base = (base * base) % M;
}
return res;
}
int main() {
ll T, N, M, i, res;
cin>>T;
while(T--) {
cin>>N>>M;
res=0;
for(i=1; i<=N; ++i)
{
res+=modularPower(i, i, M);
res%=M;
}
cout<<res<<endl;
}
return 0;
}
But this code exceeds the time limit.
How do I optimise it?
Thanks!