title: Approach and Code for o(log n) solution
body: <p>f(N) = 0^0 + 1^1 + 2^2 + 3^3 + 4^4 + ... + N^N. </p>
  
  <p>I want to calculate (<strong>f(N) mod M</strong>).</p>
  
  <p>These are the constraints.</p>
  
  <ul>
  <li>1 ≤ N ≤ 10^9 </li>
  <li>1 ≤ M ≤ 10^3</li>
  </ul>
  
  <p>Here is my code</p>
  
  <pre><code>test=int(input())
  ans = 0
  
  for cases in range(test):
      arr=[int(x) for x in input().split()]
      N=arr[0]
      mod=arr[1]
  
      #ret=sum([int(y**y) for y in range(N+1)])
      #ans=ret
  
      for i in range(1,N+1):
          ans = (ans + pow(i,i,mod))%mod
      print (ans)
  </code></pre>
  
  <p>I tried another approach but in vain.
  Here is code for that</p>
  
  <pre><code>from functools import reduce
  test=int(input())
  answer=0
  for cases in range(test):
      arr=[int(x) for x in input().split()]
      N=arr[0]
      mod=arr[1]
  
      answer = reduce(lambda K,N: x+pow(N,N), range(1,N+1)) % M
  
      print(answer)
  </code></pre>