Skip to content
Related Articles

Related Articles

Check if a number can be represented as difference of two positive perfect cubes
  • Last Updated : 14 May, 2021

Given a positive integer N, the task is to check whether N can be represented as the difference between two positive perfect cubes or not. If found to be true, then print “Yes”. Otherwise, print “No”.

Examples:

Input: N = 124
Output: Yes
Explanation: Since 124 can be represented as (125 – 1) = (53 – 13). Therefore, print Yes.

Input: N = 4
Output: No

Approach: The idea to solve the given problem is to store the perfect cubes of all numbers from 1 to X, where X is the maximum integer for which the difference between X3 and (X – 1)3 is at most N, in a Map and check if N can be represented as the difference of two numbers present in the Map or not. 
Follow the steps below to solve the problem:



  • Initialize an ordered map, say cubes, to store the perfect cubes of first X natural numbers in sorted order.
  • Traverse the map and check for the pair having a difference equal to N. If there exists any such pair, then print “Yes”. Otherwise, print “No”.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if the number N
// can be represented as a difference
// between two perfect cubes or not
void differenceOfTwoPerfectCubes(int N)
{
    // Stores the perfect cubes
    // of first X natural numbers
    map<int, int> cubes;
 
    for (int i = 1;
         (i * i * i) - ((i - 1) * (i - 1) * (i - 1)) <= N;
         i++) {
 
        cubes[i * i * i] = 1;
    }
 
    map<int, int>::iterator itr;
 
    // Traverse the map
    for (itr = cubes.begin(); itr != cubes.end(); itr++) {
 
        // Stores the first number
        int firstNumber = itr->first;
 
        // Stores the second number
        int secondNumber = N + itr->first;
 
        // Search the pair for the second
        // number to obtain difference N
        // from the Map
        if (cubes.find(secondNumber) != cubes.end()) {
            cout << "Yes";
            return;
        }
    }
 
    // If N cannot be represented
    // as difference between two
    // positive perfect cubes
    cout << "No";
}
 
// Driver Code
int main()
{
    int N = 124;
    differenceOfTwoPerfectCubes(N);
 
    return 0;
}

Java




// Java program for the above approach
import java.util.*;
class GFG
{
 
  // Function to check if N can be represented
  // as difference of two perfect cubes or not
  public static void differenceOfTwoPerfectCubes(int N)
  {
 
    // Stores the perfect cubes
    // of first N natural numbers
    HashMap<Integer, Integer> cubes = new HashMap<>();
    for (int i = 1; (i * i * i) - ((i - 1) * (i - 1) * (i - 1)) <= N; i++)
      cubes.put((i * i * i), 1);
 
    // Traverse the map
    Iterator<Map.Entry<Integer, Integer> > itr
      = cubes.entrySet().iterator();
    while (itr.hasNext())
    {
      Map.Entry<Integer, Integer> entry = itr.next();
 
      // Stores first number
      int firstNumber = entry.getKey();
 
      // Stores second number
      int secondNumber = N + entry.getKey();
 
      // Search the pair for the second
      // number to obtain differnce N from the Map
      if (cubes.containsKey(secondNumber))
      {
        System.out.println("Yes");
        return;
      }
    }
 
    // If N cannot be represented as
    // difference of two positive perfect cubes
    System.out.println("No");
  }
 
  // Driver code
  public static void main(String[] args)
  {
    int N = 124;
 
    // Function call to check if N
    // can be represented as
    // sum of two perfect cubes or not
    differenceOfTwoPerfectCubes(N);
  }
}
 
// This code is contributed by shailjapriya.

Python3




# Python3 program for the above approach
 
# Function to check if the number N
# can be represented as a difference
# between two perfect cubes or not
def differenceOfTwoPerfectCubes(N):
 
    # Stores the perfect cubes
    # of first X natural numbers
    cubes = {}
 
    i = 1
    while ((i * i * i) - ((i - 1) * (i - 1) * (i - 1)) <= N):
        cubes[i * i * i] = 1
        i += 1
 
    # Traverse the map
    for itr in cubes.keys():
 
        # Stores the first number
        firstNumber = itr
 
        # Stores the second number
        secondNumber = N + itr
 
        # Search the pair for the second
        # number to obtain difference N
        # from the Map
        if ((secondNumber) in cubes):
            print("Yes")
            return
 
    # If N cannot be represented
    # as difference between two
    # positive perfect cubes
    print("No")
 
# Driver Code
if __name__ == "__main__":
 
    N = 124
    differenceOfTwoPerfectCubes(N)
 
    # This code is contributed by ukasp.

C#




// C# program for the above approch
using System;
using System.Collections.Generic;
using System.Linq;
 
class GFG{
     
// Function to check if N can be represented
// as difference of two perfect cubes or not
public static void differenceOfTwoPerfectCubes(int N)
{
     
    // Stores the perfect cubes
    // of first N natural numbers
    Dictionary<int,
               int> cubes = new Dictionary<int,
                                           int>();
    for(int i = 1;
            (i * i * i) - ((i - 1) *
            (i - 1) * (i - 1)) <= N;
            i++)
        cubes.Add((i * i * i), 1);
 
    // Traverse the map
    foreach(KeyValuePair<int, int> entry in cubes)
    {
         
        // Stores first number
        int firstNumber = entry.Key;
 
        // Stores second number
        int secondNumber = N + entry.Key;
 
        // Search the pair for the second
        // number to obtain differnce N from the Map
        if (cubes.ContainsKey(secondNumber))
        {
            Console.Write("Yes");
            return;
        }
    }
 
    // If N cannot be represented as
    // difference of two positive perfect cubes
    Console.Write("No");
}
 
// Driver code
static void Main()
{
    int N = 124;
 
    // Function call to check if N
    // can be represented as
    // sum of two perfect cubes or not
    differenceOfTwoPerfectCubes(N);
}
}
 
// This code is contributed by abhinavjain194

Javascript




<script>
 
// Javascript program for the above approach
 
// Function to check if the number N
// can be represented as a difference
// between two perfect cubes or not
function differenceOfTwoPerfectCubes(N)
{
    // Stores the perfect cubes
    // of first X natural numbers
    var cubes = new Map();
 
    for (var i = 1;
         (i * i * i) - ((i - 1) * (i - 1) * (i - 1)) <= N;
         i++) {
 
        cubes.set(i * i * i, 1);
    }
 
    var ans = false;
 
    cubes.forEach((value, key) => {
         // Stores the first number
        var firstNumber = key;
 
        // Stores the second number
        var secondNumber = N + key;
 
        // Search the pair for the second
        // number to obtain difference N
        // from the Map
        if (cubes.has(secondNumber)) {
            document.write( "Yes");
            ans = true;
            return;
        }
    });
 
    if(ans)
    {
        return;
    }
     
 
    // If N cannot be represented
    // as difference between two
    // positive perfect cubes
    document.write( "No");
}
 
// Driver Code
var N = 124;
differenceOfTwoPerfectCubes(N);
 
 
</script>
Output: 
Yes

 

Time Complexity: O(∛N*log N)
Auxiliary Space: O(∛N)

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :