TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
|
C++ Program to find Binary Exponent Iteratively and Recursively. More...
#include <iostream>
Go to the source code of this file.
Functions | |
int | binExpo (int a, int b) |
int | binExpo_alt (int a, int b) |
int | main () |
Main function. | |
C++ Program to find Binary Exponent Iteratively and Recursively.
Calculate \(a^b\) in \(O(\log(b))\) by converting \(b\) to a binary number. Binary exponentiation is also known as exponentiation by squaring.
Example: 10 in base 2 is 1010.
\begin{eqnarray*} 2^{10_d} &=& 2^{1010_b} = 2^8 * 2^2\\ 2^1 &=& 2\\ 2^2 &=& (2^1)^2 = 2^2 = 4\\ 2^4 &=& (2^2)^2 = 4^2 = 16\\ 2^8 &=& (2^4)^2 = 16^2 = 256\\ \end{eqnarray*}
Hence to calculate 2^10 we only need to multiply \(2^8\) and \(2^2\) skipping \(2^1\) and \(2^4\).
Definition in file binary_exponent.cpp.
int binExpo | ( | int | a, |
int | b ) |
Recursive function to calculate exponent in \(O(\log(n))\) using binary exponent.
Definition at line 28 of file binary_exponent.cpp.
int binExpo_alt | ( | int | a, |
int | b ) |
Iterative function to calculate exponent in \(O(\log(n))\) using binary exponent.
Definition at line 42 of file binary_exponent.cpp.
int main | ( | void | ) |
Main function.
Give two numbers a, b
int resIterate = binExpo_alt(a, b);
Result of a^b (where '^' denotes exponentiation)
std::cout << resIterate << std::endl;
Definition at line 55 of file binary_exponent.cpp.