Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
Solved

# Raising and integer to a power

Posted on 1997-12-31
Medium Priority
1,824 Views
What is the common way in C to raise an integer value to a power. ie. FORTRAN = INT**3 which will raise the value 'INT' to the power of 3.
0
Question by:cummings
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points
• 2

LVL 84

Expert Comment

ID: 1256881
FORTRAN = INT*INT*INT;
or
#include <math.h>
FORTRAN = pow(INT,3.0); /* which actually does a float power */
or
for( p=3,FORTRAN=1; p>0; p-=1 ){ FORTRAN *= INT; }
or
for( p=3,FORTRAN=1; p>0; p>>=1 ){
FORTRAN *= FORTRAN;
if( p&1 ){ FORTRAN *= INT; }
}

0

Accepted Solution

rjh107 earned 150 total points
ID: 1256882
If you are not concerned with speed you could use the library function z = pow(x,y) (z=x^y) which involves converting integers to doubles and back again.

A somewhat faster method is included in snippets(http://www.snippets.org/) called IPOW.C which raises a double to an integer power and I'm sure you could convert this to an integer to an integral power

OR if you want ultimate speed, have lots of memory and only need to raise to one power set up a lookup table, ie a big array containing pre calculated values using one of above methods. So to find 43^7 you would set up an array called Pow3 and use z=Pow7(43)
0

LVL 84

Expert Comment

ID: 1256883
oops, got that last example backwards.
(it works for 3, but not if your power changes when reversed)

for( p=3,i=INT,FORTRAN=1; p>0; p>>=1 ){
if( p&1 ){ FORTRAN *= i; }
i *= i;
}
0

Author Comment

ID: 1256884
I ended up by writing my own function as it only involves a couple of checks and a 'for' loop. Thay you for your response.

John
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…