Open In App

Check if given number is perfect cube

Last Updated : 12 Jul, 2025
Comments
Improve
Suggest changes
9 Likes
Like
Report

Given a number N, the task is to check whether the given number N is a perfect cube or not. 
Examples:  

Input: N = 216 
Output: Yes 
Explanation: 
As 216 = 6*6*6. Therefore the cube root of 216 is 6.

Input: N = 100 
Output: No 

Naive Approach:

The idea is to check for each number from 1 to N if the cube of any of these numbers equals N. If so, then that number is the cube root of N and the N is a perfect cube.

Below is the implementation of the above approach:  

C++
// C++ program to check whether the given
// number N is the perfect cube or not
#include <bits/stdc++.h>
using namespace std;

// Function to check if a number
// is a perfect Cube or not
bool perfectCube(int n)
{
    int cube;

    // Iterate from 1-N
    for (int i; i <= n; i++)
    {
        // Find the cube of
        // every number
        cube = i * i * i;

        // Check if cube equals
        // N or not
        if (cube == n)
            return true;        
        else if (cube > n)
            return false;
    }
}

// Driver code
int main()
{
    int n = 216;
    perfectCube(n)? cout << "Yes" : cout << "No ";
    return 0;
}
Java
public class GFG {

    // Function to check if a number
    // is a perfect Cube or not
    public static boolean perfectCube(int n) {
        int cube;

        // Iterate from 1-N
        for (int i = 1; i <= n; i++) {
            // Find the cube of
            // every number
            cube = i * i * i;

            // Check if cube equals
            // N or not
            if (cube == n)
                return true;
            else if (cube > n)
                return false;
        }
        return false;
    }

    // Driver code
    public static void main(String[] args) {
        int n = 216;
        System.out.println(perfectCube(n) ? "Yes" : "No");
    }
}
Python
# Function to check if a number
# is a perfect Cube or not
def perfect_cube(n):
    # Iterate from 1-N
    for i in range(1, n+1):
        # Find the cube of
        # every number
        cube = i ** 3

        # Check if cube equals
        # N or not
        if cube == n:
            return True
        elif cube > n:
            return False
    return False

# Driver code
n = 216
print("Yes" if perfect_cube(n) else "No")
C#
using System;

class GFG {

    // Function to check if a number
    // is a perfect Cube or not
    static bool PerfectCube(int n) {
        int cube;

        // Iterate from 1-N
        for (int i = 1; i <= n; i++) {
            // Find the cube of
            // every number
            cube = i * i * i;

            // Check if cube equals
            // N or not
            if (cube == n)
                return true;
            else if (cube > n)
                return false;
        }
        return false;
    }

    // Driver code
    static void Main() {
        int n = 216;
        Console.WriteLine(PerfectCube(n) ? "Yes" : "No");
    }
}
JavaScript
// Function to check if a number
// is a perfect Cube or not
function perfectCube(n) {
    let cube;

    // Iterate from 1-N
    for (let i = 1; i <= n; i++) {
        // Find the cube of
        // every number
        cube = i * i * i;

        // Check if cube equals
        // N or not
        if (cube === n)
            return true;
        else if (cube > n)
            return false;
    }
    return false;
}

// Driver code
let n = 216;
console.log(perfectCube(n) ? "Yes" : "No");

Output
Yes

Time Complexity: O(N)
Auxiliary Space: O(1)

Using Build-in Functions:

The idea is to use the inbuilt function (cbrt()) to find the cube root of a number which returns floor value of the cube root of the number N. If the cube of this number equals N, then N is a perfect cube otherwise N is not a perfect cube.

Below is the implementation of the above approach: 

C++
#include <bits/stdc++.h>
using namespace std;

// Function to check if a number is
// a perfect Cube using inbuilt function
bool perfectCube(int n)
{
    int x = round(cbrt(n));

    // If cube of cube_root is equals to n,
    // then print Yes else print No
    return (x * x * x == n);
}

// Driver's code
int main()
{
    int n = 125;
    perfectCube(n)? cout << "Yes" : cout << "No";
    return 0;
}
Java
public class GFG {

    // Function to check if a number is
    // a perfect Cube using inbuilt function
    public static boolean perfectCube(int n) {
        int x = (int) Math.round(Math.cbrt(n));

        // If cube of cube_root is equals to n,
        // then print Yes else print No
        return (x * x * x == n);
    }

    // Driver's code
    public static void main(String[] args) {
        int n = 125;
        System.out.println(perfectCube(n) ? "Yes" : "No");
    }
}
Python
# Function to check if a number is
# a perfect Cube using inbuilt function
def perfect_cube(n):
    x = round(n ** (1/3))

    # If cube of cube_root is equals to n,
    # then print Yes else print No
    return (x * x * x == n)

# Driver's code
n = 125
print("Yes" if perfect_cube(n) else "No")
C#
using System;

class GFG {

    // Function to check if a number is
    // a perfect Cube using inbuilt function
    static bool PerfectCube(int n) {
        int x = (int) Math.Round(Math.Cbrt(n));

        // If cube of cube_root is equals to n,
        // then print Yes else print No
        return (x * x * x == n);
    }

    // Driver's code
    static void Main() {
        int n = 125;
        Console.WriteLine(PerfectCube(n) ? "Yes" : "No");
    }
}
JavaScript
// Function to check if a number is
// a perfect Cube using inbuilt function
function perfectCube(n) {
    let x = Math.round(Math.cbrt(n));

    // If cube of cube_root is equals to n,
    // then print Yes else print No
    return (x * x * x === n);
}

// Driver's code
let n = 125;
console.log(perfectCube(n) ? "Yes" : "No");

Output
Yes

Time Complexity: O(log N) because using inbuilt cbrt function
Auxiliary Space: O(1)

Using Prime Factors :

Find all the Prime Factors of the given number N using the approach in this article.

  1. Store the frequency of all the prime factors obtained above in a Hash Map.
  2. Traverse the Hash Map and if the frequency of every prime factors is not a multiple of 3, then the given number N is not a perfect cube.

Below is the implementation of the above approach:  

C++
// C++ program to check if a number
// is a perfect cube using prime factors
#include<bits/stdc++.h>
using namespace std;

// Function to check if a 
// number is perfect cube
bool perfectCube (int n)
{
    // Find all prime factors and fill their
    // frequencies in a map
    unordered_map<int, int> mp;
    while (n % 2 == 0)
    {
        mp[2]++; 
        n /= 2;
    }
    for(int i = 3; i <= sqrt(n); i += 2)
    {
        while (n % i == 0)
        {
            mp[i]++;
            n /= i;
        }
    }
    if (n > 2)
        mp[n]++;

    // Check if all frequencies are multiples of 3
    for(auto x : mp)
        if (x.second % 3 != 0)
            return false;
    return true;
}

// Driver Code
int main()
{
    int n = 216;
    perfectCube(n)? cout << "True" : cout << "False";
    return 0;
}
Java
import java.util.*;

public class GFG {

    // Function to check if a 
    // number is perfect cube
    public static boolean perfectCube(int n) {
        Map<Integer, Integer> mp = new HashMap<>();
        while (n % 2 == 0) {
            mp.put(2, mp.getOrDefault(2, 0) + 1);
            n /= 2;
        }
        for (int i = 3; i <= Math.sqrt(n); i += 2) {
            while (n % i == 0) {
                mp.put(i, mp.getOrDefault(i, 0) + 1);
                n /= i;
            }
        }
        if (n > 2)
            mp.put(n, mp.getOrDefault(n, 0) + 1);

        // Check if all frequencies are multiples of 3
        for (Map.Entry<Integer, Integer> entry : mp.entrySet())
            if (entry.getValue() % 3 != 0)
                return false;
        return true;
    }

    // Driver Code
    public static void main(String[] args) {
        int n = 216;
        System.out.println(perfectCube(n) ? "True" : "False");
    }
}
Python
# Function to check if a 
# number is perfect cube
def perfect_cube(n):
    from collections import defaultdict
    import math
    
    mp = defaultdict(int)
    while n % 2 == 0:
        mp[2] += 1
        n //= 2
    for i in range(3, int(math.sqrt(n)) + 1, 2):
        while n % i == 0:
            mp[i] += 1
            n //= i
    if n > 2:
        mp[n] += 1

    # Check if all frequencies are multiples of 3
    for freq in mp.values():
        if freq % 3 != 0:
            return False
    return True

# Driver Code
n = 216
print("True" if perfect_cube(n) else "False")
C#
using System;
using System.Collections.Generic;

class GFG {

    // Function to check if a 
    // number is perfect cube
    static bool PerfectCube(int n) {
        Dictionary<int, int> mp = new Dictionary<int, int>();
        while (n % 2 == 0) {
            if (!mp.ContainsKey(2))
                mp[2] = 0;
            mp[2]++;
            n /= 2;
        }
        for (int i = 3; i <= Math.Sqrt(n); i += 2) {
            while (n % i == 0) {
                if (!mp.ContainsKey(i))
                    mp[i] = 0;
                mp[i]++;
                n /= i;
            }
        }
        if (n > 2) {
            if (!mp.ContainsKey(n))
                mp[n] = 0;
            mp[n]++;
        }

        // Check if all frequencies are multiples of 3
        foreach (var x in mp)
            if (x.Value % 3 != 0)
                return false;
        return true;
    }

    // Driver Code
    static void Main() {
        int n = 216;
        Console.WriteLine(PerfectCube(n) ? "True" : "False");
    }
}
JavaScript
// Function to check if a 
// number is perfect cube
function perfectCube(n) {
    const mp = {};
    while (n % 2 === 0) {
        mp[2] = (mp[2] || 0) + 1;
        n /= 2;
    }
    for (let i = 3; i <= Math.sqrt(n); i += 2) {
        while (n % i === 0) {
            mp[i] = (mp[i] || 0) + 1;
            n /= i;
        }
    }
    if (n > 2)
        mp[n] = (mp[n] || 0) + 1;

    // Check if all frequencies are multiples of 3
    for (const key in mp)
        if (mp[key] % 3 !== 0)
            return false;
    return true;
}

// Driver Code
const n = 216;
console.log(perfectCube(n) ? "True" : "False");

Output
True

The idea is to use the Binary Search technique where we will be searching in a range of [1, N] iteratively by dividing the range halve every time until we get the resultant output.

  1. Initialize two variables, left and right, to 0 and the given number, respectively.
  2. While left is less than or equal to right follow the below steps.
  3. Compute the mid point and cube value.
  4. If cube is equal to N then return N, else change the left and right pointers accordingly.
  5. If no perfect cube is found in the above steps, return false, indicating that the given number is not a perfect cube.
C++
#include <iostream>
using namespace std;

bool isPerfectCube(int num)
{
    long left = 0;
    long right = num;
    while (left <= right) {
        long mid = left + (right - left) / 2;
        long cube = mid * mid * mid;
        if (cube == num) {
            return true;
        }
        else if (cube < num) {
            left = mid + 1;
        }
        else {
            right = mid - 1;
        }
    }
    return false;
}

int main()
{
    if (isPerfectCube(729))
        cout << "Yes" << endl;
    else
        cout << "No" << endl;

    return 0;
}
Java
public class GFG {

    // Function to check if a number is a perfect cube
    public static boolean isPerfectCube(int num) {
        long left = 0;
        long right = num;
        while (left <= right) {
            long mid = left + (right - left) / 2;
            long cube = mid * mid * mid;
            if (cube == num) {
                return true;
            } else if (cube < num) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        if (isPerfectCube(729))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
Python
# Function to check if a number is a perfect cube
def is_perfect_cube(num):
    left = 0
    right = num
    while left <= right:
        mid = left + (right - left) // 2
        cube = mid * mid * mid
        if cube == num:
            return True
        elif cube < num:
            left = mid + 1
        else:
            right = mid - 1
    return False

if is_perfect_cube(729):
    print("Yes")
else:
    print("No")
C#
using System;

class GFG {

    // Function to check if a number is a perfect cube
    public static bool IsPerfectCube(int num) {
        long left = 0;
        long right = num;
        while (left <= right) {
            long mid = left + (right - left) / 2;
            long cube = mid * mid * mid;
            if (cube == num) {
                return true;
            } else if (cube < num) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return false;
    }

    public static void Main() {
        if (IsPerfectCube(729))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }
}
JavaScript
// Function to check if a number is a perfect cube
function isPerfectCube(num) {
    let left = 0;
    let right = num;
    while (left <= right) {
        let mid = left + Math.floor((right - left) / 2);
        let cube = mid * mid * mid;
        if (cube === num) {
            return true;
        } else if (cube < num) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    return false;
}

if (isPerfectCube(729)) {
    console.log("Yes");
} else {
    console.log("No");
}

Output
Yes

Time Complexity : O(log N)
Auxiliary Space : O(1)

Using Mathematical Fact:

Every perfect cube can n (say n = x^3) can be written as sum of x consecutive odd numbers.

1^3 = 1 = 1
2^3 = 8 = 3 + 5
3^3 = 27 = 7 + 9 + 11
4^3 = 64 = 13 + 15 + 17 + 19
5^3 = 125 = 21 + 23 + 25 + 27 + 29
6^3 = 216 = 31 + 33 + 35 + 37 + 39 + 41

If you take a closer look, you can notice that we consider different set of consecutive odd numbers for every cube.

C++
#include <iostream>
using namespace std;

bool isPerfectCube(int n) {
    int sum = 0;
    int odd = 1;
    for (int count = 1; sum < n; count++) {
        sum = 0;
      
        // Check if current value of count is 
        // cube root of n
        for (int i = 0; i < count; i++) {
            sum += odd;
            odd += 2;
        }
        if (sum == n) return true;
    }
    return false;
}

int main() {
    for (int n = 1; n <= 100; n++) {
        if (isPerfectCube(n)) {
            cout << n << " ";
        }
    }

    return 0;
}
Java
public class Main {
    public static boolean isPerfectCube(int n) {
        int sum = 0;
        int odd = 1;
        for (int count = 1; sum < n; count++) {
            sum = 0;

            // Check if current value of count is 
            // cube root of n
            for (int i = 0; i < count; i++) {
                sum += odd;
                odd += 2;
            }
            if (sum == n) return true;
        }
        return false;
    }

    public static void main(String[] args) {
        for (int n = 1; n <= 100; n++) {
            if (isPerfectCube(n)) {
                System.out.print(n + " ");
            }
        }
    }
}
Python
def isPerfectCube(n):
    sum = 0
    odd = 1
    count = 1
    while sum < n:
        sum = 0
        
        # Check if current value of count is 
        # cube root of n
        for i in range(count):
            sum += odd
            odd += 2
        
        if sum == n:
            return True
        count += 1
    return False

def main():
    for n in range(1, 101):
        if isPerfectCube(n):
            print(n, end=" ")

main()
C#
using System;

class Program {
    public static bool IsPerfectCube(int n) {
        int sum = 0;
        int odd = 1;
        for (int count = 1; sum < n; count++) {
            sum = 0;

            // Check if current value of count is 
            // cube root of n
            for (int i = 0; i < count; i++) {
                sum += odd;
                odd += 2;
            }
            if (sum == n) return true;
        }
        return false;
    }

    static void Main() {
        for (int n = 1; n <= 100; n++) {
            if (IsPerfectCube(n)) {
                Console.Write(n + " ");
            }
        }
    }
}
JavaScript
function isPerfectCube(n) {
    let sum = 0;
    let odd = 1;
    for (let count = 1; sum < n; count++) {
        sum = 0;

        // Check if current value of count is 
        // cube root of n
        for (let i = 0; i < count; i++) {
            sum += odd;
            odd += 2;
        }
        if (sum === n) return true;
    }
    return false;
}

function main() {
    for (let n = 1; n <= 100; n++) {
        if (isPerfectCube(n)) {
            console.log(n + " ");
        }
    }
}

main();

Output
1 8 27 64 

How does this work?

Let n be perfect square and its square root be x.

We can write x^3 = n

We can also say the following
(x^2) * x = n^3
(x^2 + x^2 + x^2 .......... x-times) = n^3

If x is an odd number:
Examples:
x = 3, we can write the above as ((x^2 - 1) + x^2 + (x^2 + 1)) = n [Sum of 3 Consecutive Odd numbers]
For example say x = 5, we can write it as ((x^2 - 2) + (x^2 - 1) + x^2 + (x^2 + 1) + (x^2 + 2)) = n [Sum of 5 Consecutive Odd Numbers]
In General, ((x^2 - i + 1) + (x^2 - i + 2) ........ + x^2 + .......... (x^2 + i - 1) + (x^2 + i - 2)) where i is floor(x/2)

If x is an even number:
Examples:
x = 2, we can write the above as ((x^2 - 1) + (x^2 + 1)) = n [Sum of 2 Consecutive Odd numbers]
For example say x = 4, we can write it as ((x^2 - 2) + (x^2 - 1) + (x^2 + 1) + (x^2 + 2)) = n [Sum of 4 Consecutive Odd Numbers]
In General, ((x^2 - i) + (x^2 - i + 1) ........ (x^2 + i ) + (x^2 + i)) where i is x/2


Time Complexity : If we take a closer look, we mainly generate odd numbers 1 to a number. The number of times the innermost statement is executed is equal to the number of odd numbers generated. For example of n = 125, we generate all numbers from 1 to 29. If n = x^3, then the maximum odd numbers generated is close to x^2 + x (as explained above). We can upper bound the total iterations by O(Log n). We have explained how is the time complexity of checking if a number is perfect square is O(Log n) using the mathematical approach in the last approach discussed here.


Article Tags :

Explore