Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

power function in O(log(n)) time c++

#include <bits/stdc++.h>

using namespace std;

long long power(long long num, long long n){
 	if(n == 0)return 1;
  	long long tmp = power(num, n / 2);
  	tmp = tmp * tmp;
  	if(n % 2 == 0)return tmp;
  	return tmp * num;
}

int main() {
    cout << power(3,4); // outputs 81 since 3^4 is 81
}
 
PREVIOUS NEXT
Tagged: #power #function #time
ADD COMMENT
Topic
Name
1+5 =