Question

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.

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;

}

For any integer n > 0, n!(n factorial) is defined as the
product
n * n - 1 * n − 2 … * 2 * 1.
And 0! is defined to be 1
Create function that takes n as input and computes then returns
the accurate value for:
n!= n * n - 1 * n − 2 … * 2 * 1
prompt the user to enter an integer n, call functions to compute
the accurate value for...

1. Given an
n-element array A, Algorithm X executes an
O(n)-time computation for each even
number in A and an O(log n)-time computation for
each odd number in A.
What is the best-case running time of Algorithm X?
What is the worst-case running time of Algorithm X?
2. Given an array,
A, of n integers, give an O(n)-time algorithm that finds
the longest subarray of A such that all the numbers in that
subarray are in sorted order. Your algorithm...

ADVERTISEMENT

Get Answers For Free

Most questions answered within 1 hours.

ADVERTISEMENT

asked 11 minutes ago

asked 36 minutes ago

asked 38 minutes ago

asked 49 minutes ago

asked 50 minutes ago

asked 55 minutes ago

asked 58 minutes ago

asked 1 hour ago

asked 1 hour ago

asked 1 hour ago

asked 2 hours ago

asked 2 hours ago