What is Binary Exponentiation
Hey, Guys in this part we are going to know about what is Binary Exponentiation and how we can apply this concept in our programs.
If you have to calculate x25 , first basic approach is multiply x by itself 24 times. But if x is large enough (in millions), even just one multiplication is time consuming and also the complexicity of this approach is O(n). Can we have better option, Yes here we introduce you a better algorithm known "Binary Exponentiation" , this algo does same work in the complexicity of O(log(n)). Let see how it works.
Binary Exponentiation
The complexity of this algorithm is we have to solve powers of a, and then have to do at most multiplications for getting the final answer.
The following approach expresses as same idea:
an= 1(an2)2(an−12)2⋅a,if n =0,if n>0 and n even,if n>0 and n odd
Implementation
Iterative version of Binary Exponentiation:-
To have a breif and clear concept here, see below-
Video explanation
Recursive version of Binary Exponentiation:-
Complexity
The basic brute force approach takes O(n) multiplications to calculate a^n.
Following operations involves in binary exponentiation approach:
- O(log(n)) multiplication to keep track of powers
- Maximum O(log (n)) multiplications to get final result
- O(log(n)) left shift operations
- let consider O(log(a)*log(a)) be the time complexity for multiply two numbers.
In reality, the actual time complexity comparison:
- Brute force: (n*log(a)*log(a))
- Binary exponentiation: (log(n)*log(n)*log(a))
That why Binary exponentiation recommended againts BruteForce approach.
Modular Exponentiation
Sometimes when you have question in which value overflow may occurs due to large a or n values.Therefore, in general we calculate the power of large numbers using modulo or modular exponentiation.
It is much similar to binary exponentiation but a single difference is that ,it involves modulo operations.
The concept of modular multiplication is :- a*b=((a%m)*(b%m))%m
Now we can use the same code of binary exponentiation, and just replace every multiplication with a modular multiplication.
Let see a program in c++.
Practice Problems
May these Information will be useful for you,
Have a Nice Day๐๐๐.
✌️
ReplyDeleteGuru ji ๐ค
ReplyDelete✌
ReplyDeleteone of the best๐
ReplyDelete