if you mean the least significant or rightmost digits, this can be done using modular multiplication. This is O (N) complexity and does not require any special bignum data types.
#include <cmath> #include <cstdio> //returns ((base ^ exponent) % mod) int modularExponentiation(int base, int exponent, int mod){ int result = 1; for(int i = 0; i < exponent; i++){ result = (result * base) % mod; } return result; } int firstKDigitsOfNToThePowerOfN(int k, int n){ return modularExponentiation(n, n, pow(10, k)); } int main(){ int n = 11; int result = firstKDigitsOfNToThePowerOfN(3, n); printf("%d", result); }
This will print 611, the first three digits 11 ^ 11 = 285311670611.
This implementation is suitable for N values ββless than sqrt (INT_MAX), which will change, but on my machine and language it exceeds 46,000.
Also, if it so happens that your INT_MAX is less than (10 ^ k) ^ 2, you can change modularExponentiation to handle any N that can fit in int:
int modularExponentiation(int base, int exponent, int mod){ int result = 1; for(int i = 0; i < exponent; i++){ result = (result * (base % mod)) % mod;
if O (n) is not enough time for you, we can use the property of raising to the power that A ^ (2 * C) = (A ^ C) ^ 2 and get the logarithmic efficiency.
//returns ((base ^ exponent) % mod) int modularExponentiation(int base, int exponent, int mod){ if (exponent == 0){return 1;} if (exponent == 1){return base % mod;} if (exponent % 2 == 1){ return ((base % mod) * modularExponentiation(base, exponent-1, mod)) % mod; } else{ int newBase = modularExponentiation(base, exponent / 2, mod); return (newBase * newBase) % mod; } }