0% found this document useful (0 votes)
8 views3 pages

Daa 2

second

Uploaded by

Sumit Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views3 pages

Daa 2

second

Uploaded by

Sumit Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING

Experiment 2
Student Name: Sumit Kumar UID: 22BCS16614
Branch: BE-CSE Section/Group: 902 -A
Semester: 5th Date of Performance: 30/07/24
Subject Name: DAA Subject Code: 22CSH311

1. Aim: Code implement power function in O(logn) time complexity.

2. Objective: To implement power function in O(logn) time complexity.

3. Algorithm :

 Declare the power function to compute base raised to the power a.


 In main, declare variables base, a, and result
 Prompt the user to enter the base number, Read the base value using scanf.
 Prompt the user to enter the power number, Read the exponent value using
scanf.
 Call the power function with base and a, storing the result in result.
 Print the result in the format: "base to the power a is result.
 If a is 0, return 1.
 If a is even, compute hp recursively and return hp * hp; if odd, return base *
power(base, a - 1).
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

4. Code:
#include <stdio.h>
int power(int n, int m);
int main()
{
int base, a, result;
printf("Enter the base number: ");
scanf("%d", &base);
printf("Enter power number: ");
scanf("%d", &a);
result = power(base, a);
printf("%d to the power %d is %d", base, a, result);
return 0;
}
int power(int base, int a)
{
if (a == 0)
return 1;
if (a % 2 == 0) {
int hp = power(base, a / 2);
return hp * hp;
} else {
return base * power(base, a - 1); }
}
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

5. Output:

6. Time Complexity: O(logn)

7. Learning Outcome:
 Learn how to compute the power of a number in O(logn) time by using
efficient recursive techniques.
 Understand how to apply recursion and divide-and-conquer strategies to
handle both even and odd exponents effectively.
 Master setting up and managing base cases in recursion to ensure accurate
results for edge cases like an exponent of zero.
 Discover how to optimize recursive calls by reducing the problem size
logarithmically to improve computation efficiency.
 Apply efficient exponentiation techniques to real-world problems and
algorithms, such as those in cryptography and numerical computations.

You might also like