This looks like Python, so I’ll assume that’s what you’re using (you should tag your question with the language you’re using).
The big problem is that i**i
is humongous, so Python is using big integers to keep track of everything. Since 2e6^(2e6) has 12602060 digits, that’s too much to compute quickly (and way more than the 10 digits you need). This also means that my suggestion of moving the modulus into the loop probably wouldn’t have helped.
The solution is to take the modulus while you’re taking the exponentiation (for details see Modular exponentiation. Some implementations are here. Using Python makes this simpler, since you don’t need to worry about integer overflow (which, ironically, is what caused your original problem).
But Python makes this even easier, since pow
allows you to specify an optional modulus. So you could rewrite your original code as:
n = int(input())
if ( 1<=n<=2e6 ):
s = 0
for i in range(1,n+1):
s += pow(i,i,10**10)
print(s%(10**10))
But we can simplify this further. Python also includes a sum
function, so you could use a list comprehension and rewrite the above as
n = int(input())
if ( 1<=n<=2e6 ):
s = sum( pow(i,i,10**10) for i in range(1,n+1) )
print(s%(10**10))
But it’s silly to assign a variable for only one step. So you’d rewrite that as
n = int(input())
if ( 1<=n<=2e6 ):
print(sum( pow(i,i,10**10) for i in range(1,n+1) ) % 10**10)
But you may prefer to use the command line interface for Python, and not worry about checking the input:
sum( pow(i,i,10**10) for i in range(1,2*10**6+1) ) % 10**10