Check if a number can be represented as difference of two positive perfect cubes
Last Updated :
07 Nov, 2023
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 1:
Idea: Solve the given problem is to storing 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++
#include <bits/stdc++.h>
using namespace std;
void differenceOfTwoPerfectCubes( int N)
{
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;
for (itr = cubes.begin(); itr != cubes.end(); itr++) {
int firstNumber = itr->first;
int secondNumber = N + itr->first;
if (cubes.find(secondNumber) != cubes.end()) {
cout << "Yes" ;
return ;
}
}
cout << "No" ;
}
int main()
{
int N = 124;
differenceOfTwoPerfectCubes(N);
return 0;
}
|
Java
import java.util.*;
class GFG
{
public static void differenceOfTwoPerfectCubes( int N)
{
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 );
Iterator<Map.Entry<Integer, Integer> > itr
= cubes.entrySet().iterator();
while (itr.hasNext())
{
Map.Entry<Integer, Integer> entry = itr.next();
int firstNumber = entry.getKey();
int secondNumber = N + entry.getKey();
if (cubes.containsKey(secondNumber))
{
System.out.println( "Yes" );
return ;
}
}
System.out.println( "No" );
}
public static void main(String[] args)
{
int N = 124 ;
differenceOfTwoPerfectCubes(N);
}
}
|
Python3
def differenceOfTwoPerfectCubes(N):
cubes = {}
i = 1
while ((i * i * i) - ((i - 1 ) * (i - 1 ) * (i - 1 )) < = N):
cubes[i * i * i] = 1
i + = 1
for itr in cubes.keys():
firstNumber = itr
secondNumber = N + itr
if ((secondNumber) in cubes):
print ( "Yes" )
return
print ( "No" )
if __name__ = = "__main__" :
N = 124
differenceOfTwoPerfectCubes(N)
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class GFG{
public static void differenceOfTwoPerfectCubes( int N)
{
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);
foreach (KeyValuePair< int , int > entry in cubes)
{
int firstNumber = entry.Key;
int secondNumber = N + entry.Key;
if (cubes.ContainsKey(secondNumber))
{
Console.Write( "Yes" );
return ;
}
}
Console.Write( "No" );
}
static void Main()
{
int N = 124;
differenceOfTwoPerfectCubes(N);
}
}
|
Javascript
<script>
function differenceOfTwoPerfectCubes(N)
{
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) => {
var firstNumber = key;
var secondNumber = N + key;
if (cubes.has(secondNumber)) {
document.write( "Yes" );
ans = true ;
return ;
}
});
if (ans)
{
return ;
}
document.write( "No" );
}
var N = 124;
differenceOfTwoPerfectCubes(N);
</script>
|
Time Complexity: O(?N*log N)
Auxiliary Space: O(?N)
Approach 2:
Idea: Generating all possible combinations of two perfect cubes and checking if their difference is equal to the given number N.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
bool differenceOfTwoPerfectCubes( int N)
{
vector< int > cubes;
for ( int i = 1; i <= 100; i++) {
cubes.push_back(i * i * i);
}
int n = cubes.size();
for ( int i = 0; i < n; i++) {
for ( int j = i + 1; j < n; j++) {
int diff = cubes[j] - cubes[i];
if (diff == N) {
return true ;
}
}
}
return false ;
}
int main()
{
int N = 124;
if (differenceOfTwoPerfectCubes(N)) {
cout << "Yes" ;
}
else {
cout << "No" ;
}
return 0;
}
|
Java
import java.util.ArrayList;
import java.util.List;
public class Main {
static boolean differenceOfTwoPerfectCubes( int N) {
List<Integer> cubes = new ArrayList<>();
for ( int i = 1 ; i <= 100 ; i++) {
cubes.add(i * i * i);
}
int n = cubes.size();
for ( int i = 0 ; i < n; i++) {
for ( int j = i + 1 ; j < n; j++) {
int diff = cubes.get(j) - cubes.get(i);
if (diff == N) {
return true ;
}
}
}
return false ;
}
public static void main(String[] args) {
int N = 124 ;
if (differenceOfTwoPerfectCubes(N)) {
System.out.println( "Yes" );
}
else {
System.out.println( "No" );
}
}
}
|
Python3
import math
def isPerfectCube(N):
cubeRoot = int ( round (N * * ( 1.0 / 3.0 )))
return cubeRoot * * 3 = = N
def differenceOfTwoPerfectCubes(N):
cubes = []
for i in range ( 1 , 101 ):
cubes.append(i * i * i)
n = len (cubes)
for i in range (n):
for j in range (i + 1 , n):
diff = cubes[j] - cubes[i]
if diff = = N:
return True
return False
if __name__ = = "__main__" :
N = 4
if differenceOfTwoPerfectCubes(N):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
using System.Collections.Generic;
class MainClass
{
static bool DifferenceOfTwoPerfectCubes( int N)
{
List< int > cubes = new List< int >();
for ( int i = 1; i <= 100; i++) {
cubes.Add(i * i * i);
}
int n = cubes.Count;
for ( int i = 0; i < n; i++) {
for ( int j = i + 1; j < n; j++) {
int diff = cubes[j] - cubes[i];
if (diff == N) {
return true ;
}
}
}
return false ;
}
static void Main( string [] args) {
int N = 124;
if (DifferenceOfTwoPerfectCubes(N)) {
Console.WriteLine( "Yes" );
}
else {
Console.WriteLine( "No" );
}
}
}
|
Javascript
function differenceOfTwoPerfectCubes(N) {
let cubes = [];
for (let i = 1; i <= 100; i++) {
cubes.push(i * i * i);
}
let n = cubes.length;
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
let diff = cubes[j] - cubes[i];
if (diff == N) {
return true ;
}
}
}
return false ;
}
let N = 124;
if (differenceOfTwoPerfectCubes(N)) {
console.log( "Yes" );
} else {
console.log( "No" );
}
|
Output:
Yes
Time Complexity: O(N^(1/3))
Auxiliary Space: O(N^(1/3))
as we are storing all the perfect cubes less than N^(1/3) in a map
Approach 3 : Hash Set
Idea : Use Hash Set to store all possible values of the difference between two perfect cubes up to a certain limit.
Next, check if the given number N is presnt int hash or not.
Implementation :
C++
#include<bits/stdc++.h>
using namespace std;
bool isPerfectCube( int n)
{
int cube_root = round(cbrt(
n));
return (
cube_root * cube_root * cube_root
== n);
}
bool checkDifference( int n)
{
unordered_set< int > cubes;
int cube_limit = round(cbrt(n)) + 1;
for ( int i = 1; i <= cube_limit; i++) {
for ( int j = 1; j <= cube_limit; j++) {
int cube_diff = i * i * i - j * j * j;
if (cube_diff == n) {
return true ;
}
else if (cube_diff > n) {
break ;
}
else {
cubes.insert(cube_diff);
}
}
}
return (cubes.count(n) > 0);
}
int main()
{
int n = 124;
if (checkDifference(n) && !isPerfectCube(n)) {
cout << "Yes" << endl;
}
else {
cout << "No" << endl;
}
return 0;
}
|
Java
import java.util.HashSet;
public class PerfectCubeAndDifference {
static boolean isPerfectCube( int n) {
int cube_root = ( int ) Math.round(Math.cbrt(n));
return (cube_root * cube_root * cube_root == n);
}
static boolean checkDifference( int n) {
HashSet<Integer> cubes = new HashSet<>();
int cube_limit = ( int ) Math.round(Math.cbrt(n)) + 1 ;
for ( int i = 1 ; i <= cube_limit; i++) {
for ( int j = 1 ; j <= cube_limit; j++) {
int cube_diff = i * i * i - j * j * j;
if (cube_diff == n) {
return true ;
} else if (cube_diff > n) {
break ;
} else {
cubes.add(cube_diff);
}
}
}
return cubes.contains(n);
}
public static void main(String[] args) {
int n = 124 ;
if (checkDifference(n) && !isPerfectCube(n)) {
System.out.println( "Yes" );
} else {
System.out.println( "No" );
}
}
}
|
Python
def isPerfectCube(n):
cube_root = round (n * * ( 1 / 3 ))
return cube_root * * 3 = = n
def checkDifference(n):
cubes = set ()
cube_limit = round (n * * ( 1 / 3 )) + 1
for i in range ( 1 , int (cube_limit)):
for j in range ( 1 , int (cube_limit)):
cube_diff = i * * 3 - j * * 3
cubes.add(cube_diff)
return n in cubes
n = 124
if checkDifference(n) and not isPerfectCube(n):
print ( "No" )
else :
print ( "Yes" )
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static bool IsPerfectCube( int n)
{
int cubeRoot = ( int )Math.Round(Math.Pow(n, 1.0 / 3.0));
return (cubeRoot * cubeRoot * cubeRoot == n);
}
static bool CheckDifference( int n)
{
HashSet< int > cubes = new HashSet< int >();
int cubeLimit = ( int )Math.Round(Math.Pow(n, 1.0 / 3.0)) + 1;
for ( int i = 1; i <= cubeLimit; i++)
{
for ( int j = 1; j <= cubeLimit; j++)
{
int cubeDiff = i * i * i - j * j * j;
if (cubeDiff == n)
{
return true ;
}
else if (cubeDiff > n)
{
break ;
}
else
{
cubes.Add(cubeDiff);
}
}
}
return cubes.Contains(n);
}
static void Main( string [] args)
{
int n = 124;
if (CheckDifference(n) && !IsPerfectCube(n))
{
Console.WriteLine( "Yes" );
}
else
{
Console.WriteLine( "No" );
}
}
}
|
Javascript
function isPerfectCube(n) {
let cube_root = Math.round(Math.cbrt(n));
return (cube_root * cube_root * cube_root === n);
}
function checkDifference(n) {
let cubes = new Set();
let cube_limit = Math.round(Math.cbrt(n)) + 1;
for (let i = 1; i <= cube_limit; i++) {
for (let j = 1; j <= cube_limit; j++) {
let cube_diff = i * i * i - j * j * j;
if (cube_diff === n) {
return true ;
} else if (cube_diff > n) {
break ;
} else {
cubes.add(cube_diff);
}
}
}
return cubes.has(n);
}
let n = 124;
if (checkDifference(n) && !isPerfectCube(n)) {
console.log( "Yes" );
} else {
console.log( "No" );
}
|
Output:
Yes
Time Complexity: O(n^(2/3))
Auxiliary Space: O(n^(1/3))
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...