c - Optimized way to handle extremely large number without using external library -
optimized way handle value of n^n (1 ≤ n ≤ 10^9)
i used long long int
it's not enough value might (1000^1000)
searched , found gmp library
http://gmplib.org/ , bigint class
don't wanna use them. i looking numerical method handle this.
i need print first , last k (1 ≤ k ≤ 9) digits of n^n
for first k digits getting shown below (it's bit ugly way of doing it)
num = pow(n,n); while(num){ arr[i++] = num%10; num /= 10; digit++; } while(digit > 0){ j=digit; j--; if(count<k){ printf("%lld",arr[j]); count++; } digit--; }
and last k digits using num % 10^k
below.
findk=pow(10,k); lastdigits = num % findk; enter code here
maximum value of k 9. need 18 digits @ max. think of getting 18 digits without solving complete n^n expression.
any idea/suggestion??
finding least significant digits (last k digits) easy because of property of modular arithmetic, says: (n*n)%m == (n%m * n%m)%m
, code shown bluepixy followed exponentiation squaring method work finding k
lsds.
now, significant digits (1st k digits) of n^n
can found in way:
know, n^n = 10^(n log n)
so if calculate n log (n)
number of format xxxx.yyyy
, have use number power of 10, understandable xxxx or integer part of number add xxxx zeros after 10, not important you! means, if calculate 10^0.yyyy
, significants digits looking for. solution this:
double r = n * log10 (n); r = r - (long long) r; //so taking fractional part double v = pow(10, r); int powerk = 1; (int i=0; i<k; i++) powerk *=10; v *= powerk; //now print 1st k digits v
Comments
Post a Comment