Jump to content
  • Advertisement
Sign in to follow this  
namingway

creating a power function in C++

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Advertisement
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 this post


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

return 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 this post


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

return ans

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

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

Admiral

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!