My Report (&Account)

Dynamic Programming Test – 1


Correct Answer: 2 points | Wrong: -1 point
Grades: A* (100% score) | A (80%-99%) | B (60%-80%) | C (40%-60%) | D (0%-40%)
advertisement

1. Recursive approach to find power of a number is preferred over iterative approach.

2. What will be the output for following code?

float power(float x, int y) 
{ 
	float temp; 
	if( y==0) 
	return 1; 
	temp = power(x, y/2);	 
	if (y%2 == 0) 
		return temp*temp; 
	else
	{ 
		if(y > 0) 
			return x*temp*temp; 
		else
			return (temp*temp)/x; 
	} 
} 
int main() 
{ 
	float x = 2; 
	int y = -3; 
	printf("%f", power(x, y)); 
	return 0; 
} 

3. Which of the following correctly implements iterative code for finding power of a number?

4. What is the space complexity of the given code?

#include<stdio.h> 
int power(int x,  int y) 
{ 
	if (y == 0) 
		return 1; 
	else if (y%2 == 0) 
		return power(x, y/2)*power(x, y/2); 
	else
		return x*power(x, y/2)*power(x, y/2); 
} 
int main() 
{ 
	int x = 2; 
    int y = 3; 

	printf("%d", power(x, y)); 
	return 0; 
} 

5. Recursive program to raise an integer x to power y uses which of the following algorithm?

6. What will be the output for following code?

#include<stdio.h> 
int func(int x,  int y) 
{ 
	if (y == 0) 
		return 1; 
	else if (y%2 == 0) 
		return func(x, y/2)*func(x, y/2); 
	else
		return x*func(x, y/2)*func(x, y/2); 
} 
int main() 
{ 
	int x = 2; 
    int y = 3; 

	printf("%d", func(x, y)); 
	return 0; 
} 

7. What is the advantage of iterative code for finding power of number over recursive code?

8. What will be the time complexity of the following code which raises an integer x to the power y?

#include<stdio.h> 
int power(int x,  int y) 
{ 
	if (y == 0) 
		return 1; 
	else if (y%2 == 0) 
		return power(x, y/2)*power(x, y/2); 
	else
		return x*power(x, y/2)*power(x, y/2); 
} 
int main() 
{ 
	int x = 2; 
    int y = 3; 

	printf("%d", power(x, y)); 
	return 0; 
} 

9. What will be the time complexity of the following code?

#include<stdio.h> 
int power(int x, int y) 
{ 
    int temp; 
    if( y == 0) 
        return 1; 
    temp = power(x, y/2); 
    if (y%2 == 0) 
        return temp*temp; 
    else
        return x*temp*temp; 
} 
int main() 
{ 
	int x = 2; 
    int y = 3; 

	printf("%d", power(x, y)); 
	return 0; 
} 

10. What is the least time in which we can raise a number x to power y?


 

Start practicing “1000 MCQs on DAA”, and once you are ready, you can take tests on all topics by attempting our “DAA Test Series”.

advertisement
advertisement
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.