简体   繁体   中英

c++ : correct way to calculate power for large no

I am trying to calculate 65^17 using c++. I wrote following code but getting wrong value when 65^11 . What is the correct way to calculate the answer ? ( ie 65^17)

Code :

long double data= 1;
int m_ne=17;
int i_data=65;
for(int i=1;i<= m_ne;i++)
{
     data =  data  * (i_data);
     std::cout.precision(15);
     std::cout<<" "<<std::fixed <<data<<std::endl;
 }

output:

65.000000000000000
 4225.000000000000000
 274625.000000000000000
 17850625.000000000000000
 1160290625.000000000000000
 75418890625.000000000000000
 4902227890625.000000000000000
 318644812890625.000000000000000
 20711912837890625.000000000000000
 1346274334462890625.000000000000000
 87507831740087890624.000000000000000

I tried following options but all in vain

1. data = floor( data +0.5) * i_data ;        

2. data = floor( data +0.5) * floor (i_data + 0.5 ) ;        
By declaring i_data as float .

3.
data =  data * i_data ;        
data = floor ( data + 0.5 )

I read post about the double but I am not getting solution .

C++ itself does not support what you are trying to do with its standard data types. You would need at least 104 bits to represent every integer from 0 to 67^17.

If you feel an approximation is good enough for you, the best you can do is use the long double version of the included power function:

#include <cmath>

and

::std::cout << ::std::powl(65, 17) << ::std::endl;

You will not get a correct output however, since 65^17 is odd (the last decimal digit is a 5), and therefore would require a floating point type with at least a 104 bit mantissa (which long double usually does not have).

To get a correct answer, will need to use an higher precision library, such as GMP , which has types that can hold way more than the 104 bits you reqire and provides its own, fast exponentiation functions like this .

There is the pow function. http://www.cplusplus.com/reference/cmath/pow/ :

Just include

#include <math.h> 

or

 #include <cmath> 

And then

pow(65,17);

You should use Bignum library gmp to handle large data types which can't be handled by standard c++ types. http://gmplib.org/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM