# Challenge

#1

I figured out the challenge in chapter five after some thought. However, I’d like to ask if anyone has similar challenges for me to practice with. Thanks!

#2

Okay, here is one.

Write a function that computes the integral power of a given number in an efficient way.

For example: 7 raised to the power of 12 := 7 * 7 * 7 * … * 7 (multiply 7 by itself 12 times)

A naive approach would just multiply 7 by itself 12 times.

Hint: think about how you can reduce the number of multiplications required.

#3

Ibex10,

That was a little easy for the example. Granted, it would be a different story to write an efficient one for all possibilities.

[code]#include <stdio.h>

double workaround(test)
{
int value2 = test * test;
double value3 = value2 * test;
double value4 = value3 * value3;
double value5 = value4 * value4;
return value5;
}

``````int main(int argc, const char * argv[])
``````

{
double value1 = 31;
double answer = workaround(value1);
printf(“The answer to Ibex’s test is: %f\n”,answer);
return 0;
}[/code]

I’m thinking the most efficient would be to use the “pow” function in <math.h>.

This worked as a double (not as a long or int) but I must admit I’m still very unsure of data types in C.

#4

Ibex,

This would be the most efficient way:

[code]#include <stdio.h>

int workaround(int x,int n)
{
int result = 1;

``````while (n){
if (n&1){
result *= x;
}
n >>=1 ;
x *= x;
}

return result;
``````

}

``````int main(int argc, const char * argv[])
``````

{

``````printf("Enter the base number:\n");
int b;
scanf("%d", &b);
printf("Enter the exponent number:\n");
int e;
scanf("%d", &e);
int answer = workaround(b,e);
printf("The answer to Ibex's test is: %d\n",answer);
return 0;
``````

}[/code]

I stumbled across the bitwise way to check for odd/even and then tried to work it into an if/then/else statement but was having trouble so i ended up borrowing this part:

```while (n){ if (n&1){ result *= x; } n >>=1 ; x *= x;```