Public Group

# creating a power function in C++

This topic is 4245 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I'm creating a few different maths functions and I can't figure out how to get a 'to the power of' function. I looked over the math.h header but that didn't help much.

##### Share on other sites
In the cmath.h header you'll find a function called pow() used like so:

//2 to the power of 5
int result = pow(2, 5);

Hope this helps.

##### Share on other sites
So you want to program a power function on your own ?
If your exponent is an integer number, then you can perform "Exponentiation by squaring".

##### Share on other sites
I looked at that link, but couldn't get it working. Maybe I'll try again later.

##### Share on other sites
the easy way would be something like:
power(x,p)
ans = 1
for(i = 0; i < p; i++)
ans *= x

return ans

##### Share on other sites
well that worked perfectly :D thank you very much!

##### Share on other sites
Quote:
 Original post by stonemetalthe easy way would be something like:power(x,p)ans = 1for(i = 0; i < p; i++)ans *= xreturn ans

That's also a naive, inefficient way of doing it. A somewhat better algorithm is binary exponentiation.

EDIT: I see that link has already been linked. Why did you give up on it so easily?

##### Share on other sites
Quote:
Original post by Sneftel
Quote:
 Original post by stonemetalthe easy way would be something like:power(x,p)ans = 1for(i = 0; i < p; i++)ans *= xreturn ans

That's also a naive, inefficient way of doing it.

Not to mention that it is only valid for non-negative integer powers.

• ### What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

• 15
• 14
• 46
• 22
• 27
• ### Forum Statistics

• Total Topics
634051
• Total Posts
3015247
×