I am writing a program in C++ where I have to calculate the value of n^n where 1<=n<=10^9. But even if I use long long type to store the result, the answer is calculated just till n=15.
At n=16, a floating point exception arises and and after that results show negative values. Can anybody tell me what is wrong with the code?
long long c;
c=(long long)n;
for(int i=2;i<=n;i++)
c*=n;
cout<<c<<endl;
If you are getting negative values then you are overflowing the variable. You need to use a data type that has a larger range, one that is sufficient to hold the numbers you wish to calculate. If your system does not come with such a data type (and I rather suspect that
long longis as big as you will get) then you will need to use a bignum class.Looking more closely at the numbers in your question, I think that many standard bignum classes will not be able to calculate nn for n=109. Are you sure you wrote the problem down correctly?