I am writing a program where I need to know only the first k (k can be anywhere between 1-5) numbers of another big number which can be represented as n^n where n is a very large number.
Currently I am actually calculating n^n and then parsing it as a string. I wonder if there is a better more fast method exists.
There are two possibilities.
If you want the first k leading digits (as in: the leading digit of 12345 is 1), then you can use the fact that
so you compute the fractional part
fofn*Log10(n), and then the first k digits of10^fwill be your result. This works for numbers up to about 10^10 before round-off errors start kicking in if you use double precision. For example, forn = 2^20,f = 0.57466709...,10^f = 3.755494...so your first 5 digits are 37554. Forn = 4,f = 0.4082...,10^f = 2.56so your first digit is 2.If you want the first k trailing digits (as in: the trailing digit of 12345 is 5), then you can use modular arithmetic. I would use the squaring trick:
Taking n=2^20 as an example again, we find that
result = 88576. For n=4, we havefactor = 1, 4, 6andresult = 1, 1, 6so the answer is 6.