# Fastest raise to power.

This tip submitted by Ezzetabi on 2005-03-18 16:31:04. It has been viewed 53952 times.
Rating of 5.6 with 211 votes

If you need raising to power some non standard object, like matrices or something overloaded with a integer exponent you can use this algorith:

a any type that know operator*, b int
```      (a*a)^(b/2)         if b is even
a^b =
a*(a*a)*(int)^(b/2) if b is odd
using a recursive function your calculation will be faster (overall with big exponents) than the usual way.

A little example code:
double mpow (double, int);
double mpow2(double, int);

double mpow(double b, int exp)
{
if (exp < 0)
{
b = 1/b;
exp *= -1;
}

return mpow2(b,exp);
}

double mpow2(double b, int exp)
{
if (exp > 2)
{
if (exp%2)
return b*mpow(b*b,(int)exp/2);
else
return mpow(b*b,exp/2);
}
else if (2 == exp)
return b*b;
else if (1 == exp)
return b;

return 1.0; // exp == 0
}
This example is about floats, so it is nothing more than the usual pow(), yet if you need raising to power try to avoid a*a*a*a*...*a as that is really slow.

10
9
8
7
6
5
4321

More tips

Help your fellow programmers! Add a tip!

function abTest(element_name_sets) {
var element_to_show;
var element_count = element_name_sets.length;
var i;
for ( i = 0; i < element_count; i++ )
{
if ( Math.random() <= 1 / ( element_count - i ) ) {
break;
}
}
var element_name_set = element_name_sets[ i ];
for ( i = 0; i < element_name_set.length; i++ )
{
element_to_show = document.getElementById( element_name_set[ i ] );
element_to_show.style.display = "block";
}
}
//abTest( [["old-ad", "new-ad"]] );

Popular pages

Jumping into C++, the Cprogramming.com ebook
How to learn C++ or C
C Tutorial
C++ Tutorial
5 ways you can learn to program faster
The 5 most common problems new programmers face
How to set up a compiler
How to make a game in 48 hours

Advertising | Privacy policy |
Copyright © 2019 Cprogramming.com | Contact | About

```