Index: Course Name: DAA Lab
Index: Course Name: DAA Lab
Index: Course Name: DAA Lab
INDEX
Experiment 1.2
Aim: Develop a program for implementation of power function and determine that complexity should be
O(log n).
Procedure/Algorithm:
a) Start with the base number base and the exponent exp.
b) Initialize a variable result to 1 to store the final result.
c) While exp is greater than 0, do the following:
• If exp is odd, multiply result by base.
• Sqaure base
• Halve exp by integer division
d) Return the value of result as the power of the number.
Sample Code:
#include <iostream>
using namespace std;
int power(int x, unsigned int n)
{
int temp;
if (n == 0)
return 1;
temp = power(x, n / 2);
if (n % 2 == 0)
Name: UID:
Course Name: DAA Lab
return temp * temp;
else
return x * temp * temp;
}
int main() {
int x;
cout<<"Enter value of x"<<endl;
cin>>x;
int n;
cout<<"Enter value of n"<<endl;
cin>>n;
cout<<power(x,n);
return 0;
}
Observations/Outcome:
Name: UID: