0

In C, I am trying a few different things, but am not sure which is most efficient. I am trying to have a power function returns

Originally I had

long long rhs = num % (long long) pow(10, pos);

but this gave errors as the power became high.

I substituted powl to return a long double, which works flawlessly in returning powers up to the largest value of long long

long long rhs = num % (long long) powl(10, pos);

However, I am worried that this may not be the most efficient way to get powers of 10, which are reused in other parts of the programs.

For getting powers of ten to divide a long long up to its maximum value, should I continue using the powl cast to long long method or use a function that only returns long long like i did below. Which is more efficient?

long long pow10(int exp)
{
 long long pow = 1;

 for(exp = exp; exp > 0; exp--)
 {

   pow *= 10;
 }

  return pow;

}//pow10
Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
apache
  • 567
  • 1
  • 5
  • 9

2 Answers2

1

Performance wise, a look-up table will be fastest:

long long pow10( unsigned int )
{
    static const long long lookup[]
    { 
        1LL, 
        10LL, 
        100LL, 
        1000LL, 
        10000LL, 
        1000000LL,
        10000000LL, 
        100000000LL, 
        1000000000LL, 
        10000000000LL, 
        100000000000LL, 
        1000000000000LL, 
        10000000000000LL, 
        100000000000000LL, 
        1000000000000000LL, 
        10000000000000000LL, 
        100000000000000000LL, 
        1000000000000000000LL 
    } ; 

    return( lookup[exp] ) ;
}
Clifford
  • 88,407
  • 13
  • 85
  • 165
1

You can use divide and conquer. This won't be faster than a pure table look up, but it doesn't need to be modified if the width of long long changes, either. If you want to detect overflow, you will need log10(ULLONG_MAX), and compare the incoming exp argument against it.

unsigned long long pow10 (int exp) {
    static long long odd[] = { 1, 10 };
    unsigned long long x = 10;
    unsigned long long y = 1;
    while (exp > 1) {
        x *= x;
        y *= odd[exp % 2];
        exp /= 2;
    }
    return (exp > 0) ? x * y : !exp;
}
jxh
  • 69,070
  • 8
  • 110
  • 193