How do you write POWER function?

I just want to see yours to see how stupid my design is :D

below is the example

1
2
3
4
5
6
7
8
9
10
11
12
13
???? power(??????????) {
  ???????????????;
}

int main() {
  cout << power(5,4) << endl; //prints 625
  cout << power(5,2) << endl; //prints 25
  cout << power(5,1) << endl; //prints 5
  cout << power(5,0) << endl; //prints 1
  cout << power(5,-1) << endl; //prints 0.2
  cout << power(5,-4) << endl; //prints 0.0016
  return 0;
}
Last edited on
If your design produces the correct answer, then the only thing it may need is just efficiency. Here is mine:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
unsigned _power( unsigned val, unsigned _pow=0 ) {
	if ( _pow <= 0 )
		return 1;
	return val * _power( val, _pow-1 );
}

int main()
{
	unsigned _pow, _value;
	
	cout << "Enter a value: ";
	cin >> _value;
	cout << "Enter a power: ";
	cin >> _pow;
	cout << _power( _value, _pow ) << endl;
  	
	return 0;
}


Something like this might serve:

1
2
3
4
5
6
7
8
9
10
 double raise(double x,int n)
     {
       assert(x>0);
       double y=1.0;
       for(int i=0;i<n;i++)
       y*=x;
       for(int i=0;i>n;i--)
       y/=x;
       return y;
    }

The problem with this is that power index should be a whole number
unlike pow() which returns a double from two doubles.
btw Smac do you mean this?
if ( _pow <= 0 )
return 1;
Last edited on
@Smac89:
If your design produces the correct answer, then the only thing it may need is just efficiency.


Actually, using recursion will overload the stack for large values. That's why recursion shouldn't be used only when strictly necessary. However, it's not going to give a longer execution time if the given input consists of low numbers.

In order to make it more efficient I recommend changing the actual recursion with a for loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>

typedef long double ld;

ld power(ld, ld);

int main(int argc, char *argv[]) {
	ld Value, Power;

	std::cout << "Enter a value: ";
	std::cin >> Value;
	std::cout << "Enter a power: ";
	std::cin >> Power;
	std::cout << power(Value, Power) << std::endl;
  	
	system("pause");
	return 0;
}

ld power(ld value, ld power) {
	ld result = 1;

	for (ld i = 0; i < power; ++i) {
		result *= value;
	}

	return (result);
}


Kind regards,
Raul Butuc
Last edited on
I normally just use the power function included in the math.h header file but if I had to create my own, it would look something like this.

1
2
3
4
5
6
7
8
9
10
11
float Power(float Base, int Power)
{
        float Return = 1;
        if ( Power > 0)
               for (int n = 0; n < Power; n++)
                      Return *= Base;
        else
               for (int n = 0; n > Power; n--)
                      Return /= Base;
        return Return;
}
Topic archived. No new replies allowed.