Open In App

Logarithm tricks for Competitive Programming

Last Updated : 01 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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++

// 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";
    }
}

                    

C

// C implementation to check that
// a integer is a power of Two
#include <stdio.h>
#include <math.h>
 
// 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))
    {
        printf("Yes");
    }
    else
    {
        printf("No");
    }
}
 
// This code is contributed by vikas_g

                    

Java

// 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

                    

Python3

# 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   

                    

C#

// 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

                    

Javascript

<script>
    // Java implementation to check that
      // a integer is a power of Two
     
    // Function to check if the number
    // is a power of two
    function isPowerOfTwo(n)
    {
        return (Math.ceil(Math.log(n) / Math.log(2)) == Math.floor(Math.log(n) / Math.log(2)));
    }
      
    let N = 8;
   
    if (isPowerOfTwo(N)) {
        document.write("Yes");
    }
    else {
        document.write("No");
    }
     
    // This code is contributed by Shubham.
</script>

                    

Output
Yes

Time Complexity: O(logn)

Auxiliary Space: O(1)

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:
 

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++

// 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;
}

                    

Java

// 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

                    

Python3

# 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

                    

C#

// C# implementation to find
// Kth root of the number
using System;
 
// Function to find the
// Kth root of the number
class GFG{
     
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()
{
    double N = 8.0;
    int K = 3;
 
    Console.Write(kthRoot(N, K));
}
}
 
// This code is contributed by vikas_g

                    

Javascript

<script>
 
// Javascript implementation to find
// Kth root of the number
 
// Function to find the
// Kth root of the number
function kthRoot(n, k)
{
    return Math.pow(k,
               (1.0 / k)
                   * (Math.log(n)
                      / Math.log(k)));
}
 
// Driver Code
var N = 8.0;
var K = 3;
document.write( kthRoot(N, K));
 
</script>

                    

Output
2

Time Complexity: O(logn)

Auxiliary Space: O(1)

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:
 

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++

// 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;
}

                    

C

// C implementation count the
// number of digits in a number
#include <stdio.h>
#include <math.h>
 
// 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;
 
    printf("%d", countDigit(N));
 
    return 0;
}
 
// This code is contributed by vikas_g

                    

Java

// Java implementation to count the
// number of digits in a number
class GFG{
 
// Function to count the
// number of digits in a number
static int countDigit(double n)
{
    return((int)Math.floor(Math.log10(n) + 1));
 
}
 
// Driver Code
public static void main(String[] args)
{
    double N = 80;
     
    System.out.println(countDigit(N));
}
}
 
// This code is contributed by vikas_g

                    

Python3

# 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

                    

C#

// C# implementation count the
// number of digits in a number
using System;
 
// Function to count the
// number of digits in a number
class GFG{
     
static int countDigit(double n)
{
    return((int)Math.Floor(Math.Log10(n) + 1));
}
 
// Driver Code
public static void Main()
{
    double N = 80;
     
    Console.Write(countDigit(N));
}
}
 
// This code is contributed by vikas_g

                    

Javascript

<script>
//Javascript implementation
 
// Function to count the
// number of digits in a number
function countDigit(n)
{
    return Math.floor(Math.log10(n) + 1);
}
 
// Driver program to test above
var n = 80;
document.write(countDigit(n));
// This code is contributed by shivani.
</script>

                    

Output
2

Time Complexity: O(logn)

Auxiliary Space: O(1)

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++

// 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;
}

                    

C

// C implementation to check if
// the number is power of K
#include <stdio.h>
#include <math.h>
 
// 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))
    {
        printf("Yes");
    }
    else
    {
        printf("No");
    }
    return 0;
}
 
// This code is contributed by vikas_g

                    

Java

// Java implementation to check if
// the number is power of K
class GFG{
 
// Function to check if
// the number is power of K
static boolean isPower(int N, int K)
{
     
    // Logarithm function to
    // calculate value
    int res1 = (int)(Math.log(N) / Math.log(K));
    double res2 = Math.log(N) / Math.log(K);
 
    // Compare to the result1
    // or result2 both are equal
    return (res1 == res2);
}
 
// Driver Code
public static void main(String[] args)
{
    int N = 8;
    int K = 2;
 
    if (isPower(N, K))
    {
        System.out.println("Yes");
    }
    else
    {
        System.out.println("No");
    }
}
}
 
// This code is contributed by vikas_g

                    

Python3

# 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

                    

C#

// C# implementation to check if
// the number is power of K
using System;
 
// Function to count the
// number of digits in a number
class GFG{
     
static bool isPower(int N, int K)
{
     
    // Logarithm function to
    // calculate value
    int res1 = (int)(Math.Log(N) / Math.Log(K));
    double res2 = Math.Log(N) / Math.Log(K);
 
    // Compare to the result1
    // or result2 both are equal
    return (res1 == res2);
}
 
// Driver Code
public static void Main()
{
    int N = 8;
    int K = 2;
 
    if (isPower(N, K))
    {
        Console.Write("Yes");
    }
    else
    {
        Console.Write("No");
    }
}
}
 
// This code is contributed by vikas_g

                    

Javascript

<script>
//Javascript Implementation
// to check if
// the number is power of K
 
// Function to check if
// the number is power of K
function isPower(N, K)
{
    // logarithm function to
    // calculate value
    var res1 = Math.floor(Math.log(N) / Math.log(K));
    var res2 = Math.log(N) / Math.log(K);
 
    // compare to the result1
    // or result2 both are equal
    return (res1 == res2);
}
 
// Driver Code
var N = 8;
var K = 2;
 
if (isPower(N, K)) {
document.write("Yes");
}
else {
document.write("No");
}
// This code is contributed by shubhamsingh10
</script>

                    

Output
Yes

Time Complexity: O(logn)

Auxiliary Space: O(1)

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++

// 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;
}

                    

C

// C implementation to find the
// previous and next power of K
#include <stdio.h>
#include <math.h>
 
// 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;
 
    printf("%d ", prevPowerofK(N, K));
    printf("%d\n", nextPowerOfK(N, K));
     
    return 0;
}
 
// This code is contributed by vikas_g

                    

Java

// Java implementation to find the
// previous and next power of K
class GFG{
 
// Function to return the highest power
// of k less than or equal to n
static int prevPowerofK(int n, int k)
{
    int p = (int)(Math.log(n) / Math.log(k));
    return (int)Math.pow(k, p);
}
 
// Function to return the smallest power
// of k greater than or equal to n
static int nextPowerOfK(int n, int k)
{
    return prevPowerofK(n, k) * k;
}
 
// Driver Code
public static void main(String[] args)
{
    int N = 7;
    int K = 2;
     
    System.out.print(prevPowerofK(N, K) + " ");
    System.out.println(nextPowerOfK(N, K));
}
}
 
// This code is contributed by vikas_g

                    

Python3

# 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

                    

C#

// C# implementation to find the
// previous and next power of K
using System;
 
// Function to count the
// number of digits in a number
class GFG{
     
// Function to return the highest power
// of k less than or equal to n
static int prevPowerofK(int n, int k)
{
    int p = (int)(Math.Log(n) / Math.Log(k));
    return (int)Math.Pow(k, p);
}
 
// Function to return the smallest power
// of k greater than or equal to n
static int nextPowerOfK(int n, int k)
{
    return prevPowerofK(n, k) * k;
 
}
 
// Driver Code
public static void Main()
{
    int N = 7;
    int K = 2;
     
    Console.Write(prevPowerofK(N, K) + " ");
    Console.Write(nextPowerOfK(N, K));
}
}
 
// This code is contributed by vikas_g

                    

Javascript

<script>
 
// Javascript implementation to find the
// previous and next power of K
 
// Function to return the highest power
// of k less than or equal to n
function prevPowerofK(n, k)
{
    let p = parseInt(Math.log(n) /
                     Math.log(k), 10);
    return Math.pow(k, p);
}
 
// Function to return the smallest power
// of k greater than or equal to n
function nextPowerOfK(n, k)
{
    return prevPowerofK(n, k) * k;
}
 
// Driver code
let N = 7;
let K = 2;
  
document.write(prevPowerofK(N, K) + " ");
document.write(nextPowerOfK(N, K));
 
// This code is contributed by rameshtravel07
 
</script>

                    

Output
4 8

Time Complexity: O(logn)

Auxiliary Space: O(1)

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:
 

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++

// 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;
}

                    

C

// C implementation to find the
// rightmost set bit
#include <stdio.h>
#include <math.h>
 
// 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;
 
    printf("%d", getFirstSetBitPos(N));
    return 0;
}
 
// This code is contributed by vikas_g

                    

Java

// Java implementation to find the
// rightmost set bit
class GFG{
 
// Function to find the rightmost
// bit set of the integer N
static int getFirstSetBitPos(int n)
{
    return (int)(Math.log(n & -n) /
                 Math.log(2)) + 1;
}
 
// Driver Code
public static void main(String[] args)
{
    int N = 8;
 
    System.out.println(getFirstSetBitPos(N));
}
}
 
// This code is contributed by vikas_g

                    

Python3

# 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

                    

C#

// C# implementation to find the
// rightmost set bit
using System;
 
class GFG{
 
// Function to find the rightmost
// bit set of the integer N
static int getFirstSetBitPos(int n)
{
    return (int)(Math.Log(n & -n) /
                 Math.Log(2)) + 1;
}
 
// Driver Code
public static void Main()
{
    int N = 8;
 
    Console.Write(getFirstSetBitPos(N));
}
}
 
// This code is contributed by vikas_g

                    

Javascript

<script>
    // Javascript implementation to find the rightmost set bit
     
    // Function to find the rightmost
    // bit set of the integer N
    function getFirstSetBitPos(n)
    {
        return parseInt(Math.log(n & -n) / Math.log(2), 10) + 1;
    }
     
    let N = 8;
  
    document.write(getFirstSetBitPos(N));
     
    // This code is contributed by mukesh07.
 
</script>

                    

Output
4

Time Complexity: O(logn)

Auxiliary Space: O(1)



Previous Article
Next Article

Similar Reads

Tips and Tricks for Competitive Programmers | Set 2 (Language to be used for Competitive Programming)
This is a question asked quite often as in which language should be preferred to be efficient in competitive programming. It is something one should not worry about as what matters is the logic, not the language. Most of the languages are more or less same, but till now the most preferred language is C++, and here are the reasons. Python Simple and
5 min read
Some useful C++ tricks for beginners in Competitive Programming
Here are some of the basic C++ tricks that every beginner in Competitive Programming should follow for increased speed. However, competitive programming can only be mastered with time and lots of practice. These tricks will just help you to save a little time during the contests which sometimes matters a lot. Using the auto keyword to declare data
3 min read
Mathematics Tricks For Competitive Programming In Python 3
Here are some of the exciting features that Python 3.8 provides for programmers in competitive programming. These new features are related to some math functions and algorithms that are frequently used by competitive programmers. The implementation of these features has the time complexity which is the same in case of a program when implemented fro
3 min read
Python Tips and Tricks for Competitive Programming
Python Programming language makes everything easier and straightforward. Effective use of its built-in libraries can save a lot of time and help with faster submissions while doing Competitive Programming. Below are few such useful tricks that every Pythonist should have at their fingertips: Converting a number into a List of digits using map() Fun
4 min read
C++ tricks for competitive programming (for C++ 11)
We have discussed some tricks in the below post. In this post, some more tricks are discussed. Writing C/C++ code efficiently in Competitive programming Although, practice is the only way that ensures increased performance in programming contests but having some tricks up your sleeve ensures an upper edge and fast debugging. 1) Checking if the numb
5 min read
Java tricks for competitive programming (for Java 8)
Although the practice is the only way that ensures increased performance in programming contests but having some tricks up your sleeve ensures an upper edge and fast debugging.1) Checking if the number is even or odd without using the % operator: Although this trick is not much better than using a % operator but is sometimes efficient (with large n
5 min read
Bit Tricks for Competitive Programming
In competitive programming or in general, some problems seem difficult but can be solved very easily with little concepts of bit magic. We have discussed some tricks below in the previous post.Bitwise Hacks for Competitive Programming One-Liner Hacks of Bit Manipulation:One-Liner CodeFunctionx&amp;1 Evaluates to 1 if the number is odd else evaluate
7 min read
Tips and Tricks for Competitive Programmers | Set 1 (For Beginners)
This article is a collection of various tips that would help beginners of Competitive programming to get an insight of things that should or shouldn’t be done. Competitive programming can only be improved by “PRACTICE, PRACTICE AND PRACTICE”. Try to solve as many questions you can solve on sites like practice.geeksforgeeks.org. This will enhance yo
6 min read
Python Tricks for Competitive Coding
Python is one such programming language that makes everything easier and straight forward. Anyone who has dabbled in python for Competitive Coding gets somewhat addicted to its many features. Here is a list of some of its cool features that I've found most useful in a competitive coding environment. The most common function of the Counter Package.
5 min read
Competitive Programming vs General Programming
Programming enthusiasts face a crossroads - Competitive Programming or General Programming? This article sheds light on the distinctions between Competitive Programming vs General Programming, offering a quick guide for those navigating the coding landscape. Whether you're aiming for speed and precision in competitions or tackling real-world projec
3 min read