Logarithm tricks for Competitive Programming

Logarithm: is the inverse function of the exponentiation which means the logarithm value of a given number x is the exponent to another number.
log_b(x) = y, \to b^{y} = x

Below are some tricks using Logarithmic function which can be handy in competitive programming.

Checking if a number is a power of two or not:

Given an integer N, the task is to check that if the number N is the power of 2.
Examples:

Input: N = 8
Output: Yes

Input: 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:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation to check that
// a integer is a power of Two
  
#include <bits/stdc++.h>
  
using namespace std;
  
// Function to check if the number
// is a power of two
bool isPowerOfTwo(int n)
{
    return (ceil(log2(n)) == floor(log2(n)));
}
  
// Driver Code
int main()
{
    int N = 8;
  
    if (isPowerOfTwo(N)) {
        cout << "Yes";
    }
    else {
        cout << "No";
    }
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation to check that 
// a integer is a power of Two 
import java.lang.Math;
  
class GFG{
      
// Function to check if the number 
// is a power of two 
public static boolean isPowerOfTwo(int n) 
    return(Math.ceil(Math.log(n) /
                     Math.log(2)) == 
          Math.floor(Math.log(n) / 
                     Math.log(2)));
      
// Driver Code 
public static void main(String[] args)
{
    int N = 8
  
    if (isPowerOfTwo(N)) 
    
        System.out.println("Yes");
    
    else 
    {
        System.out.println("No");
    
}
}
  
// This code is contributed by divyeshrabadiya07

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation to check that 
# a integer is a power of two 
import math
  
# Function to check if the number 
# is a power of two             
def isPowerOfTwo(n):
      
    return(math.ceil(math.log(n) // 
                     math.log(2)) == 
           math.floor(math.log(n) //
                      math.log(2))); 
                      
# Driver code 
if __name__=='__main__':
      
    N = 8
      
    if isPowerOfTwo(N):
        print('Yes')
    else:
        print('No')
  
# This code is contributed by rutvik_56    

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation to check that 
// a integer is a power of Two 
using System;
  
class GFG{
      
// Function to check if the number 
// is a power of two 
public static bool isPowerOfTwo(int n) 
    return(Math.Ceiling(Math.Log(n) / 
                        Math.Log(2)) == 
             Math.Floor(Math.Log(n) /
                        Math.Log(2)));
      
// Driver Code 
public static void Main(String[] args)
{
    int N = 8; 
  
    if (isPowerOfTwo(N)) 
    
        Console.WriteLine("Yes");
    
    else
    {
        Console.WriteLine("No");
    
}
}
  
// This code is contributed by 29AjayKumar

chevron_right


Output:

Yes

Kth root of a Number

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: 2

Input: 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, N^{(\frac{1}{K})} = D

Applying Log_K on both side
=> Log_K(N^{(\frac{1}{K})}) = Log_{K}(D)
=> (\frac{1}{K}) * Log_K(N) = Log_{K}(D)
=> D = K^{(\frac{1}{K}) * Log_K(N)}

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation to find
// Kth root of the number
  
#include <bits/stdc++.h>
  
using namespace std;
  
// Function to find the
// Kth root of the number
double kthRoot(double n, int k)
{
    return pow(k,
               (1.0 / k)
                   * (log(n)
                      / log(k)));
}
  
// Driver Code
int main()
{
    double N = 8.0;
    int K = 3;
  
    cout << kthRoot(N, K);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation to find
// Kth root of the number
class GFG{
  
// Function to find the
// Kth root of the number
static double kthRoot(double n, int k)
{
    return Math.pow(k, (1.0 / k) * 
                    (Math.log(n) / Math.log(k)));
}
  
// Driver Code
public static void main(String[] args)
{
    double N = 8.0;
    int K = 3;
  
    System.out.print(kthRoot(N, K));
}
}
  
// This code is contributed by shivanisinghss2110

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation to find 
# Kth root of the number 
import math
  
# Function to find the 
# Kth root of the number 
def kth_root(n, k):
      
    return(pow(k, ((1.0 / k) * (math.log(n) / 
                                math.log(k)))))
  
# Driver code
if __name__=="__main__":
      
    n = 8.0
    k = 3
      
    print(round(kth_root(n, k)))
  
# This code is contributed by dipesh99kumar

chevron_right


Output:

2

Count digits in a Number:

Given an integer N, the task is to count the digits in a number N.

Examples:

Input: N = 243
Output: 3

Input: 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:



C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation count the
// number of digits in a number
  
#include <bits/stdc++.h>
  
using namespace std;
  
// Function to count the
// number of digits in a number
int countDigit(long long n)
{
    return floor(log10(n) + 1);
}
  
// Driver Code
int main()
{
    double N = 80;
  
    cout << countDigit(N);
  
    return 0;
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation count the 
# number of digits in a number
import math
  
# Function to count the 
# number of digits in a number 
def countDigit(n):
      
    return(math.floor(math.log10(n) + 1))
  
# Driver code
if __name__=="__main__":
      
    n = 80
  
    print(countDigit(n))
  
# This code is contributed by dipesh99kumar

chevron_right


Output:

2

Check if N is a power of K or not:

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: Yes

Input: 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:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation to check if
// the number is power of K
  
#include <bits/stdc++.h>
  
using namespace std;
  
// Function to check if
// the number is power of K
bool isPower(int N, int K)
{
    // logarithm function to
    // calculate value
    int res1 = log(N) / log(K);
    double res2 = log(N) / log(K);
  
    // compare to the result1
    // or result2 both are equal
    return (res1 == res2);
}
  
// Driver Code
int main()
{
    int N = 8;
    int K = 2;
  
    if (isPower(N, K)) {
        cout << "Yes";
    }
    else {
        cout << "No";
    }
  
    return 0;
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation to check if a 
# number is a power of the other number
from math import log
  
# Function to check if 
# the number is power of K 
def isPower(n, k):
      
    # Logarithm function to 
    # calculate value 
    res1 = int(log(n) / log(k))
    res2 = log(n) / log(k)
      
    # Compare to the result1 
    # or result2 both are equal 
    return(res1 == res2)
  
# Driver code
if __name__=="__main__":
      
    n = 8
    k = 2
      
    if (isPower(n, k)):
        print("Yes")
    else:
        print("No")
  
# This code is contributed by dipesh99kumar

chevron_right


Output:

Yes

To find the power of K greater than equal to and less than equal to N:

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 8

Input: 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:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation to find the
// previous and next power of K
  
#include <bits/stdc++.h>
  
using namespace std;
  
// Function to return the highest power
// of k less than or equal to n
int prevPowerofK(int n, int k)
{
    int p = (int)(log(n) / log(k));
    return (int)pow(k, p);
}
  
// Function to return the smallest power
// of k greater than or equal to n
int nextPowerOfK(int n, int k)
{
    return prevPowerofK(n, k) * k;
}
  
// Driver Code
int main()
{
    int N = 7;
    int K = 2;
  
    cout << prevPowerofK(N, K) << " ";
  
    cout << nextPowerOfK(N, K) << endl;
    return 0;
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation to find the
# previous and next power of K 
from math import log
  
# Function to return the highest power
# of k less than or equal to n
def prevPowerofK(n, k):
      
    p = (int)(log(n) / log(k));
    return pow(k, p);
  
# Function to return the smallest power
# of k greater than or equal to n
def nextPowerOfK(n, k):
      
    return prevPowerofK(n, k) * k;
  
# Driver Code
if __name__=="__main__":
      
    N = 7
    K = 2
      
    print(prevPowerofK(N, K), end = " ")
    print(nextPowerOfK(N, K))
  
# This code is contributed by dipesh99kumar

chevron_right


Output:

4 8

To Find the position of rightmost set bit:

Given an integer N, the task is to find the position of the rightmost set bit.

Examples:

Input: N = 7
Output: 1

Input: N = 8
Output: 4

Approach:

  • Take two’s complement of the given no as all bits are reverted except the first ‘1’ from right to left (0111)
  • Do a bit-wise & with original no, this will return no with the required one only (0100)
  • Take the log2 of the no, you will get (position – 1) (2)

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation to find the
// rightmost set bit
  
#include <bits/stdc++.h>
  
using namespace std;
  
// Function to find the rightmost
// bit set of the integer N
unsigned int getFirstSetBitPos(int n)
{
    return log2(n & -n) + 1;
}
  
// Driver Code
int main()
{
    int N = 8;
  
    cout << getFirstSetBitPos(N);
    return 0;
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation to find the
# rightmost set bit
import math
  
# Function to find the rightmost
# bit set of the integer N
def getFirstSetBitPos(n):
  
    return math.log2(n & -n) + 1;
  
# Driver Code
if __name__=="__main__":
      
    N = 8
  
    print(int(getFirstSetBitPos(N)))
  
# This code is contributed by dipesh99kumar

chevron_right


Output:

4

competitive-programming-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.