Solution 1 ^ 1 + 2 ^ 2 + 3 ^ 3 + ... N ^ N

I want to calculate the sum of this expression for large N=10e9

and then modulo nom<=1000

1^1+2^2+3^3+...+N^N

I tried this approach, but still it exceeded the time I needed a better approach, please help me.

#include<bits/stdc++.h>    
using namespace std;
    int expmod(int n, int p, int m) {
       if (p == 0) return 1;
       int nm = n % m;
       long long r = expmod(nm, p / 2, m);
       r = (r * r) % m;
       if (p % 2 == 0) return r;
       return (r * nm) % m;
    }

    int main(){

       long long n,m;
        cin>>n>>m;
        long long r = 0;
        for (int i = 1; i <= n; ++i)
        r = (r + expmod(i, i, m)) % m;
        cout<<r+1<<endl;
} 

      

+3


source to share





All Articles