TheAlgorithms/C++
1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
binary_exponent.cpp
Go to the documentation of this file.
1
24
#include <iostream>
25
28
int
binExpo
(
int
a,
int
b) {
29
if
(b == 0) {
30
return
1;
31
}
32
int
res =
binExpo
(a, b / 2);
33
if
(b % 2) {
34
return
res * res * a;
35
}
else
{
36
return
res * res;
37
}
38
}
39
42
int
binExpo_alt
(
int
a,
int
b) {
43
int
res = 1;
44
while
(b > 0) {
45
if
(b % 2) {
46
res = res * a;
47
}
48
a = a * a;
49
b /= 2;
50
}
51
return
res;
52
}
53
55
int
main
() {
56
int
a, b;
58
std::cin >> a >> b;
59
if
(a == 0 && b == 0) {
60
std::cout <<
"Math error"
<< std::endl;
61
}
else
if
(b < 0) {
62
std::cout <<
"Exponent must be positive !!"
<< std::endl;
63
}
else
{
64
int
resRecurse =
binExpo
(a, b);
66
68
std::cout << resRecurse << std::endl;
70
}
71
}
binExpo_alt
int binExpo_alt(int a, int b)
Definition
binary_exponent.cpp:42
main
int main()
Main function.
Definition
binary_exponent.cpp:55
binExpo
int binExpo(int a, int b)
Definition
binary_exponent.cpp:28
math
binary_exponent.cpp
Generated by
1.12.0