![]() |
VOOZH | about |
Logarithm: is the inverse function of the exponentiation which means the logarithm value of a given number x is the exponent to another number.
Below are some tricks using Logarithmic function which can be handy in competitive programming.
Given an integer N, the task is to check that if the number N is the power of 2.
Examples:
Input: N = 8
Output: YesInput: N = 6
Output: No
Approach: A simple method for this is to simply take the log of the number on base 2, if you get an integer then the number is the power of 2.
Below is the implementation of the above approach:
Yes
Time Complexity: O(logn)
Auxiliary Space: O(1)
Given two integers N and K, the task is to find the Kth root of the number N.
Examples:
Input: N = 8, K = 3
Output: 2Input: N = 32, K = 5
Output: 2
Approach: A simple solution is to use logarithmic function to find the Kth root of the number. Below is the illustration of the approach:
Let D be our answer
then,
Applying on both side
=>
=>
=>
Below is the implementation of the above approach:
2
Time Complexity: O(logn)
Auxiliary Space: O(1)
Given an integer N, the task is to count the digits in a number N.
Examples:
Input: N = 243
Output: 3Input: N = 1000
Output: 4
Approach: The idea is to find the logarithm of the number base 10 to count the number of digits.
Below is the implementation of the above approach:
2
Time Complexity: O(logn)
Auxiliary Space: O(1)
Given two integers N and K, the task is to check if Y is power of X or not.
Examples:
Input: N = 8, K = 2
Output: YesInput: N = 27, K = 3
Output: Yes
Approach: The idea is to take log of N in base K. If it turns out to be an integer, then N is a power of K.
Below is the implementation of the above approach:
Yes
Time Complexity: O(logn)
Auxiliary Space: O(1)
Given two integers N and K, the task is to find the power of K greater than equal to and less than equal to N.
Examples:
Input: N = 7, K = 2
Output: 4 8Input: N = 18, K = 3
Output: 9 27
Approach: The idea is to find the floor value of the log K value of the given integer N, Then compute the Kth power of this number to compute the previous and next Kth power.
Below is the implementation of the above approach:
4 8
Time Complexity: O(logn)
Auxiliary Space: O(1)
Given an integer N, the task is to find the position of the rightmost set bit.
Examples:
Input: N = 7
Output: 1Input: N = 8
Output: 4
Approach:
Below is the implementation of the above approach:
4
Time Complexity: O(logn)
Auxiliary Space: O(1)