DEPARTMENT OF
COMPUTER SCIENCE &
ENGINEERING
Experiment 2
Student Name: Tushar kumar UID:22BCS16824
Branch: CSE Section/Group:IOT-643A
Semester: 5th Date of Performance: 24-07-24
Subject Name: DAA LAB Subject Code: 22CSH-311
1. Aim: Code implement power function in O(logn) time complexity.
2. Objective:
The objective here is to implement a power function in C++ that computes
x^n in O(logn) time complexity using an efficient approach called
"exponentiation by squaring".
3. Implementation/Code: #include <iostream> using namespace std;
long long power(long long x, long long n) {
if (n == 0) return 1; else if (n % 2
== 0) { long long half_pow =
power(x, n / 2); return half_pow *
half_pow;
} else { long long half_pow =
power(x, n / 2); return half_pow *
half_pow * x;
}
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
int main() { long long x = 2; long long n = 10;
long long result = power(x, n); cout << x << "^"
<< n << " = " << result << endl; return 0;
}
4. Output
5. Time Complexity
O(log n)
6. Learning Outcome
• You learn a powerful technique for computing powers efficiently.
Exponentiation by squaring reduces the number of multiplicative
operations drastically compared to a naive approach that directly
multiplies the base x by itself n times.
• You understand the importance of time complexity in algorithm design •
You develop skills in algorithmic thinking and optimization