#### Binary Exponent

```/**
* @file
* @brief C++ Program to find Binary Exponent Iteratively and Recursively.
*
* Calculate \f\$a^b\f\$ in \f\$O(\log(b))\f\$ by converting \f\$b\f\$ to a
* binary number. Binary exponentiation is also known as exponentiation by
* squaring.
* @note This is a far better approach compared to naive method which
* provide \f\$O(b)\f\$ operations.
*
* Example:
* </br>10 in base 2 is 1010.
* \f{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\\
* \f}
* Hence to calculate 2^10 we only need to multiply \f\$2^8\f\$ and \f\$2^2\f\$
* skipping \f\$2^1\f\$ and \f\$2^4\f\$.
*/

#include <iostream>

/// Recursive function to calculate exponent in \f\$O(\log(n))\f\$ using binary
/// exponent.
int binExpo(int a, int b) {
if (b == 0) {
return 1;
}
int res = binExpo(a, b / 2);
if (b % 2) {
return res * res * a;
} else {
return res * res;
}
}

/// Iterative function to calculate exponent in \f\$O(\log(n))\f\$ using binary
/// exponent.
int binExpo_alt(int a, int b) {
int res = 1;
while (b > 0) {
if (b % 2) {
res = res * a;
}
a = a * a;
b /= 2;
}
return res;
}

/// Main function
int main() {
int a, b;
/// Give two numbers a, b
std::cin >> a >> b;
if (a == 0 && b == 0) {
std::cout << "Math error" << std::endl;
} else if (b < 0) {
std::cout << "Exponent must be positive !!" << std::endl;
} else {
int resRecurse = binExpo(a, b);
/// int resIterate = binExpo_alt(a, b);

/// Result of a^b (where '^' denotes exponentiation)
std::cout << resRecurse << std::endl;
/// std::cout << resIterate << std::endl;
}
}
```
{"ft_lang_label":"__label__en","ft_lang_prob":0.528844,"math_prob":0.99941576,"size":1597,"snap":"2023-40-2023-50","text_gpt3_token_len":616,"char_repetition_ratio":0.11048336,"word_repetition_ratio":0.051446944,"special_character_ratio":0.46211648,"punctuation_ratio":0.15680474,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.99999595,"pos_list":[0,1,2,3,4],"im_url_duplicate_count":[null,null,null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2023-10-03T18:05:59Z\",\"WARC-Record-ID\":\"<urn:uuid:70e844fe-2901-4eae-954d-db22a462985a>\",\"Content-Length\":\"88679\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:b9e52a0c-6ca8-4890-a116-8ce08f57296a>\",\"WARC-Concurrent-To\":\"<urn:uuid:820d097e-5f39-439f-b773-d273e1ec46b7>\",\"WARC-IP-Address\":\"76.76.21.21\",\"WARC-Target-URI\":\"https://the-algorithms.com/algorithm/binary-exponent?lang=c-plus-plus\",\"WARC-Payload-Digest\":\"sha1:AXMX74LX7K5IHXTMX4JI4X2AD3MEUMRW\",\"WARC-Block-Digest\":\"sha1:XTHPG7VVXJ7XR5QVBVDA6NOVZ6627MUN\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2023/CC-MAIN-2023-40/CC-MAIN-2023-40_segments_1695233511170.92_warc_CC-MAIN-20231003160453-20231003190453-00256.warc.gz\"}"}