How do i determine the first n digits of an exponentiation (ab).
eg: for a = 12, b = 13 & n = 4, the first 4 digits are 1069.
How do i determine the first n digits of an exponentiation (ab).
eg: for a = 12, b = 13 & n = 4, the first 4 digits are 1069.
For this case - with magic numbers 12,13,4 in place:
#include <sstream>
#include <iomanip>
#include <cmath>
double a = 12;
int b = 13;
double result = std::pow(a,b);
std::stringstream strVal;
strVal.setf( ios::fixed, ios::floatfield );
strVal << result;
std::string output(strVal.str().substr(0,4));
output = "1069"
std::stringstream intStr(output);
int intVal;
intStr >> intVal;
intVal = 1069
EDIT:
This should work for any combination where result does not overflow double
.
The easiest way programatically to do this is to use a stringstream to convert the result of the exponentation to a string and then take the n most significant (i.e. left) characters.
if you want a way without strings then this will work:
#include <iostream>
#include <sstream>
#include <math.h>
using namespace std;
double nDigExp( double a, double b, int n )
{
stringstream ss;
ss.setf( ios::fixed, ios::floatfield );
ss << pow(a,b);
double ret;
for ( int i = 0; i < n; ++i) ret = (10 * ret) + (ss.get() - '0'); // Yeuch!!
return ret;
}
int main( )
{
double result = nDigExp( 12, 13, 4 );
cout << result << endl;
return 0;
}
But it's hardly the most elegent code. I'm sure you can improve it.
Another solution, using log10:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char **argv) {
int a = 12;
int b = 13;
int n = 4;
double x, y;
x = b * log10(a);
y = floor(pow(10, x - floor(x) + n - 1));
printf("Result: %d\n", (int)y);
return EXIT_SUCCESS;
}