"MC Felon" <paec.nwa@gmail.com> writes:
Quote:
|
how do i make a function that takes 2 numbers as arguments (1 as the number and the 2nd as the exponent) and raises that number to the power (stored as exponent) i worked this out.. though i could not get the logical statement inside the for-loop right. it's squaring itself for every one incrementation! here's the listing:
|
Let's add some assertions to understand what it is computing:
Quote:
|
double long pwr( double long num,int exp) { int y = 0;
|
/* num = n = n^(2^y) */
Quote:
|
for( y = 1;y <= exp; y++) {
|
/* num = n^(2^(y-1)) */
/* num = n^(2^y) */
/* num = n^(2^exp) */
So your function pwr(n,e) returns n^(2^e).
Now what you want is n^e.
What does this mean?
n^e = n*n*n*....*n
\_____...._/
e times n
n^e = n*(n*n*....*n
\___...._/
e-1 times n
n^e = n*(n^(e-1))
Another interesting factoid is that n^0 = 1
Therefore we could take as invariant assertion: p = n^i
/* p = n^(i-1) */
p*=n;
/* p = n*n^(i-1) = n^i */
Now, if we add as stop condition i==e, we'd get as post condition:
/* p = n^i & i = e */ ==> /* p = n^e */
which is what we want. So:
while(i!=e){
/* p = n^i) */
i++;
/* p = n^(i-1) */
p*=n;
/* p = n^i) */
}
/* p = n^e */
Remains to add the initial condition: /* i = 0 & p = n^0 */
To ensure that, we need to execute: i=0; p=1;
int pwr(unsigned int n,unsigned int e){
unsigned int i;
unsigned int p;
i=0;p=1;
/* i = 0 & p = n^0 */
while(i!=e){
/* p = n^i) */
i++;
/* p = n^(i-1) */
p*=n;
/* p = n^i) */
}
/* p = n^e */
return p;
}
--
__Pascal Bourguignon__
http://www.informatimago.com/
PLEASE NOTE: Some quantum physics theories suggest that when the
consumer is not directly observing this product, it may cease to
exist or will exist only in a vague and undetermined state.