# Power

• 01-23-2009
mrsirpoopsalot
Power
I would like not to use the function pow()
but instead write a very simple one

Code:

```long power2 (long n); { // Returns 2 raised to the power of n. }```
is there a simple formula i can use?

thank you
• 01-23-2009
tabstop
Raising a number to a power is just repeated multiplication.

(If you want 2^n, you can do even better because of the internal binary representation of the number -- multiplying by 2 in binary is just like multiplying by 10 in decimal: you just move things over.)
• 01-23-2009
laserlight
If your comment is accurate then in this case it really is very simple:
Code:

```// Returns 2 raised to the power of n. long power2(long n) {     return 1L << n; }```
However, if what you want is to implement your own version of pow(), then recall that pow() takes two arguments, not just one, and for good reason.

EDIT:
Then again, since your power2() function deals with long rather than unsigned long, it might make sense to define power2() for negative valued arguments as returning 0. A simple if statement would suffice.
• 01-24-2009
mrsirpoopsalot
what i want to do is send in a prime number
and make it a mersenne prime.
using 2^n -1

not sure how i can do that without using pow()
• 01-24-2009
laserlight
Ah, then a left shift as tabstop hinted and I demonstrated would indeed be correct. Since n would be positive, you would not have to account for negative numbers either.
• 01-24-2009
mrsirpoopsalot
Quote:

Originally Posted by laserlight
Ah, then a left shift as tabstop hinted and I demonstrated would indeed be correct. Since n would be positive, you would not have to account for negative numbers either.

i'm not sure how to do that
• 01-24-2009
laserlight
Quote:

Originally Posted by mrsirpoopsalot
i'm not sure how to do that

Read the tutorial on bitwise operations. The expression that you are looking for is (1L << n) - 1. Note that you have a pretty limited set of prime number inputs since this would quickly overflow even an unsigned long long.
• 01-24-2009
mrsirpoopsalot
I was going to test from 2 to a million numbers and if a prime number then send that prime number to the power2 function. I will work on it this weekend!
ok, i will read the tutorial thank you and i will use this expression
(1L << n) - 1
• 01-24-2009
iMalc
Quote:

Originally Posted by mrsirpoopsalot
I was going to test from 2 to a million numbers and if a prime number then send that prime number to the power2 function. I will work on it this weekend!
ok, i will read the tutorial thank you and i will use this expression
(1L << n) - 1

You wont get anywhere near 1 million unless you use a bignum library of some kind, e.g. GMP. Otherwise you'll be limited to about 2 to 31.