Check if a number can be represented as difference of two positive perfect cubes

16 Jul, 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 = 124Output: YesExplanation: Since 124 can be represented as (125 – 1) = (53 – 13). Therefore, print Yes.
Input: N = 4Output: 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++
Java
Python3
C#
Javascript
// 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 notvoid 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 Codeint main(){    int N = 124;    differenceOfTwoPerfectCubes(N);     return 0;}
// Java program for the above approachimport 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 difference 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 program for the above approach # Function to check if the number N# can be represented as a difference# between two perfect cubes or notdef 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 Codeif __name__ == "__main__":     N = 124    differenceOfTwoPerfectCubes(N)     # This code is contributed by ukasp.
// C# program for the above approachusing 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 notpublic 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 difference 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 codestatic 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
<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 notfunction 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 Codevar N = 124;differenceOfTwoPerfectCubes(N);  </script>
Yes
 
Time Complexity: O(∛N*log N)Auxiliary Space: O(∛N)
shailjapriya
ukasp
abhinavjain194
rrrtnx
arorakashish0911
saurabh1990aror
cpp-map
maths-perfect-cube
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Merge two sorted arrays with O(1) extra space
Program to print prime numbers from 1 to N.
Find next greater number with same set of digits
Segment Tree | Set 1 (Sum of given range)
Check if a number is Palindrome
Count ways to reach the n'th stair
Fizz Buzz Implementation
Count all possible paths from top left to bottom right of a mXn matrix
Product of Array except itself