I am trying to solve a problem where we have to output the the last digit of the given number n^p.
int modularExponentiation(int n, long long p, int m){
if(p == 0) return 1;
if(p & 1)
return (n % m * modularExponentiation((n*n) % m, p / 2, m) % m) % m;//line 4
return modularExponentiation((n*n) % m, p / 2, m) % m;
}
In this recursive code, here we are changing the temporary result by applying modulo in line 4. Will this not bring any change in the final answer? for example if at any intermediary stage the answer is 81^4, applying %10 at 81 and replacing it with 1, will it not change the final result?