1. You should pass your code as text
Code:
#include <stdio.h>
double mypow(double base, int exponent)
{
int k; /* A counter that initially gets set to the bitlength of exponent (and counts down afterwards) */
int kpow; /* A variable that will always equal 2 to the power k */
double result; /* Will hold intermediate and final result of the exponentiation */
int n; /* Will hold the part of the exponent that still needs to be processed */
/* If the exponent is negative, make a recursive call (once) */
if (exponent<0);
{
return 1/mypow(base, -exponent);
}
/* Determine the bitlength of the exponent, i.e. the smallest k s.t. exponent < 2^k */
k = 0;
kpow = 1;
while (kpow<exponent)
{
kpow *= 2;
k++;
}
/* Assume that the exponent equals 2^l a_l + ... + 2 a_1 + a_0
* Then left-to-right exponentiation will process the bits from a_l down to a_0
* Algorithmic invariant: result^(2^k) * base^n = base^{exponent} and 0<=n<2^k
*/
/* Initialize the result and remainder of exponent */
result = base;
n = exponent;
/* Process the exponent from left to right */
while ( k>0 )
{
kpow /= 2;
k--;
/* square */
result *= result;
/* check if bit a_k is set or not */
if ( n>=kpow )
{
/* bit to process is set */
printf("1");
/* multiply in the base */
result *= base;
/* update the exponent to reflect bit has been processed */
n -= kpow;
} else {
/* bit to process is not set */
printf("0");
/* no further work needed */
}
}
return result;
}
And do not run your program till you fix all warnings. Especially this nasty one
Code:
test.c(68): warning C4717: 'mypow' : recursive on all control paths, function will cause runtime stack overflow