Question

Foundation of computer science Let x be a real number, and n be an integer. 1....

Foundation of computer science

Let x be a real number, and n be an integer.

1. Devise an algorithm that computes x n . [Hint: First, give a procedure for computing x n when n is nonnegative by successive multiplication by x, starting with 1 until we reach n. Then, extend this procedure and use the fact that x -n = 1/x n to compute x n when n is negative.]

2. Write its corresponding program using your favorite programming language.

Homework Answers

Answer #1

1. Algorithm-

K:=1
if n≠0 then
for i:= to |n|
k:=k⋅x
if n<0 then k:=1/k
return k

2. Program in C-

double power(double x, int n)
{
    double product = 1;
    int count;
                   if(n<0) { count = count * (-1); // take absolute value of n }
                   else { count = n; }
if(n!=0)
{
    for(int i=1; i<=count; i++)
    {
        product = product * x;
    }
   if(n<0)  // if exponent is negative value then take the reciprocal of the product.
            product = 1/product;
}
else  // if exponent is zero....
      product = 1;
    return product;
}

int main()

{

double x; int n;

//take both inputs x and n from user ysing scanf function

printf("%lf", power(x,n));

return 0;

}

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions