Open In App

Check whether a number can be represented as difference of two consecutive cubes

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

Given a number N, the task is to check if the number N can be represented as the difference of two consecutive cubes or not. If Yes then print those numbers else print No.

Examples: 

Input: N = 19 
Output: 
Yes  
2 3
Explanation: 
33 – 23 = 19

Input: N = 10 
Output: No 

Approach: The key observation in the problem is that a number can be represented as difference of two consecutive cubes if and only if:

=> N = (K+1)3 – K3 
=> N = 3*K2 + 3*K + 1 
=> 12*N = 36*K2 + 36*K + 12 
=> 12*N = (6*K + 3)2 + 3 
=> 12*N – 3 = (6*K + 3)2 
which means (12*N – 3) must be a perfect square to break N into difference of two consecutive cubes.

Therefore, if the above condition holds true then we will print the numbers using a for a loop by check that for which value of i if (i+1)3 – i3 = N and print the number i and i + 1.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to print the two consecutive
// numbers whose difference is N
void print(int N)
{
    // Iterate in the range [0, 10^5]
    for (int i = 0; i < 100000; i++) {
 
        if (pow(i + 1, 3)
                - pow(i, 3)
            == N) {
 
            cout << i << ' ' << i + 1;
            return;
        }
    }
}
 
// Function to check if N is a
// perfect cube
bool isPerfectSquare(long double x)
{
    // Find floating point value of
    // square root of x.
    long double sr = sqrt(x);
 
    // If square root is an integer
    return ((sr - floor(sr)) == 0);
}
 
// Function to check whether a number
// can be represented as difference
// of two consecutive cubes
bool diffCube(int N)
{
    // Check if 12 * N - 3 is a
    // perfect square or not
    return isPerfectSquare(12 * N - 3);
}
 
// Driver Code
int main()
{
    // Given Number N
    int N = 19;
    if (diffCube(N)) {
        cout << "Yes\n";
        print(N);
    }
    else {
        cout << "No\n";
    }
    return 0;
}


Java




// Java program for the above approach
import java.util.*;
class GFG{
   
// Function to print the two consecutive
// numbers whose difference is N
static void print(int N)
{
    // Iterate in the range [0, 10^5]
    for (int i = 0; i < 100000; i++)
    {
  
        if (Math.pow(i + 1, 3) - Math.pow(i, 3) == N)
        {
            int j = i + 1;
            System.out.println(i + " " + j);
            return;
        }
    }
}
  
// Function to check if N is a
// perfect cube
static boolean isPerfectSquare(double x)
{
    // Find floating point value of
    // square root of x.
    double sr = Math.sqrt(x);
  
    // If square root is an integer
    return ((sr - Math.floor(sr)) == 0);
}
  
// Function to check whether a number
// can be represented as difference
// of two consecutive cubes
static boolean diffCube(int N)
{
    // Check if 12 * N - 3 is a
    // perfect square or not
    return isPerfectSquare(12 * N - 3);
}
  
// Driver Code
public static void main(String[] args)
{
    // Given Number N
    int N = 19;
    if (diffCube(N))
    {
        System.out.println("Yes");
        print(N);
    }
    else
    {
        System.out.println("No");
    }
}
}
 
// This code is contributed by rock_cool


Python3




# Python3 program for the above approach
import math
 
# Function to print the two consecutive
# numbers whose difference is N
def printt(N):
     
    # Iterate in the range [0, 10^5]
    for i in range(100000):
        if (pow(i + 1, 3) - pow(i, 3) == N):
            print(i, '', i + 1)
            return
         
# Function to check if N is a
# perfect cube
def isPerfectSquare(x):
     
    # Find floating povalue of
    # square root of x.
    sr = math.sqrt(x)
 
    # If square root is an integer
    return ((sr - math.floor(sr)) == 0)
 
# Function to check whether a number
# can be represented as difference
# of two consecutive cubes
def diffCube(N):
     
    # Check if 12 * N - 3 is a
    # perfect square or not
    return isPerfectSquare(12 * N - 3)
 
# Driver Code
 
# Given number N
N = 19
 
if (diffCube(N)):
    print("Yes")
    printt(N)
     
else:
    print("No")
 
# This code is contributed by sanjoy_62


C#




// C# program for the above approach
using System;
class GFG{
   
// Function to print the two consecutive
// numbers whose difference is N
static void print(int N)
{
    // Iterate in the range [0, 10^5]
    for (int i = 0; i < 100000; i++)
    {
  
        if (Math.Pow(i + 1, 3) - Math.Pow(i, 3) == N)
        {
            int j = i + 1;
            Console.WriteLine(i + " " + j);
            return;
        }
    }
}
  
// Function to check if N is a
// perfect cube
static bool isPerfectSquare(double x)
{
    // Find floating point value of
    // square root of x.
    double sr = Math.Sqrt(x);
  
    // If square root is an integer
    return ((sr - Math.Floor(sr)) == 0);
}
  
// Function to check whether a number
// can be represented as difference
// of two consecutive cubes
static bool diffCube(int N)
{
    // Check if 12 * N - 3 is a
    // perfect square or not
    return isPerfectSquare(12 * N - 3);
}
  
// Driver Code
public static void Main(String[] args)
{
    // Given Number N
    int N = 19;
    if (diffCube(N))
    {
        Console.WriteLine("Yes");
        print(N);
    }
    else
    {
        Console.WriteLine("No");
    }
}
}
 
// This code is contributed by Rajput-Ji


Javascript




<script>
 
// Javascript program for the above approach
 
// Function to print the two consecutive
// numbers whose difference is N
function print(N)
{
     
    // Iterate in the range [0, 10^5]
    for(let i = 0; i < 100000; i++)
    {
        if (parseInt(Math.pow(i + 1, 3), 10) -
            parseInt(Math.pow(i, 3), 10) == N)
        {
            document.write(i + " " + (i + 1));
            return;
        }
    }
}
 
// Function to check if N is a
// perfect cube
function isPerfectSquare(x)
{
     
    // Find floating point value of
    // square root of x.
    let sr = Math.sqrt(x);
 
    // If square root is an integer
    return ((sr - Math.floor(sr)) == 0);
}
 
// Function to check whether a number
// can be represented as difference
// of two consecutive cubes
function diffCube(N)
{
     
    // Check if 12 * N - 3 is a
    // perfect square or not
    return isPerfectSquare(12 * N - 3);
}
 
// Driver code
 
// Given Number N
let N = 19;
 
if (diffCube(N) != 0)
{
    document.write("Yes" + "</br>");
    print(N);
}
else
{
    document.write("No");
}
 
// This code is contributed by divyeshrabadiya07
 
</script>


Output

Yes
2 3


Time Complexity: O(N), where N is in the range 105 
Auxiliary Space: O(1)

Approach 2: Binary Search:

The given program is used to determine whether a given number N can be expressed as the difference of two consecutive cubes.

  •  The approach used in the program is based on the fact that the difference of two consecutive cubes can be expressed as (j^3 – i^3), where j = i + 1.
  • The program checks all possible values of i from 0 to 100000. For each value of i, it performs a binary search to find the value of j such that (j^3 – i^3) is equal to N. The search space for j is from i+1 to 100000 since j should always be greater than i. The binary search is performed by maintaining two pointers, lo and hi, that point to the left and right endpoints of the search space, respectively. The mid pointer is calculated as the average of lo and hi, and the difference (j^3 – i^3) is calculated for the mid value. If the difference is equal to N, the values of i and j are printed, and the function returns true. If the difference is less than N, the lo pointer is moved to mid+1 to search for a larger value of j. If the difference is greater than N, the hi pointer is moved to mid-1 to search for a smaller value of j. This process continues until either the pair (i, j) is found, or the search space is exhausted.
  • If no such pair (i,j) is found for any value of i, the function returns false indicating that N cannot be expressed as the difference of two consecutive cubes.
  • In the main function, a value of N=19 is given as input to the diffCube function. The function diffCube is called to determine if 19 can be expressed as the difference of two consecutive cubes. If such a pair exists, the program prints “Yes”. Otherwise, it prints “No”.

Here is the code of above approach:

C++




#include <bits/stdc++.h>
using namespace std;
 
// Function to check whether a number
// can be represented as difference
// of two consecutive cubes
bool diffCube(int N)
{
    // Iterate over the possible values of i
    for (int i = 0; i <= 100000; i++) {
        int lo = i + 1, hi = 100000, mid;
 
        // Binary search for j
        while (lo <= hi) {
            mid = lo + (hi - lo) / 2;
 
            // Check if the difference is N
            if (pow(mid, 3) - pow(i, 3) == N) {
                cout << i << " " << mid << endl;
                return true;
            }
 
            // If the difference is less than N,
            // move the left pointer
            if (pow(mid, 3) - pow(i, 3) < N)
                lo = mid + 1;
            // If the difference is greater than N,
            // move the right pointer
            else
                hi = mid - 1;
        }
    }
 
    // If no such pair is found, return false
    return false;
}
 
// Driver Code
int main()
{
    // Given Number N
    int N = 19;
    if (diffCube(N))
        cout << "Yes\n";
    else
        cout << "No\n";
    return 0;
}


Java




import java.util.*;
 
public class Main {
  // Function to check whether a number
// can be represented as difference
// of two consecutive cubes
static boolean diffCube(int N) {
    // Iterate over the possible values of i
    for (int i = 0; i <= 100000; i++) {
        int lo = i + 1, hi = 100000, mid;
 
        // Binary search for j
        while (lo <= hi) {
            mid = lo + (hi - lo) / 2;
 
            // Check if the difference is N
            if (Math.pow(mid, 3) - Math.pow(i, 3) == N) {
                System.out.println(i + " " + mid);
                return true;
            }
 
            // If the difference is less than N,
            // move the left pointer
            if (Math.pow(mid, 3) - Math.pow(i, 3) < N)
                lo = mid + 1;
            // If the difference is greater than N,
            // move the right pointer
            else
                hi = mid - 1;
        }
    }
 
    // If no such pair is found, return false
    return false;
}
 
// Driver Code
public static void main(String[] args) {
    // Given Number N
    int N = 19;
    if (diffCube(N))
        System.out.println("Yes");
    else
        System.out.println("No");
}
}


Python3




import math
 
# Function to check whether a number
# can be represented as difference
# of two consecutive cubes
def diff_cube(N):
    # Iterate over the possible values of i
    for i in range(0, 100001):
        lo, hi = i + 1, 100000
 
        # Binary search for j
        while lo <= hi:
            mid = lo + (hi - lo) // 2
 
            # Check if the difference is N
            if (mid**3 - i**3) == N:
                print(i, mid)
                return True
 
            # If the difference is less than N,
            # move the left pointer
            if (mid**3 - i**3) < N:
                lo = mid + 1
            # If the difference is greater than N,
            # move the right pointer
            else:
                hi = mid - 1
 
    # If no such pair is found, return false
    return False
 
# Driver Code
if __name__ == '__main__':
    # Given Number N
    N = 19
    if diff_cube(N):
        print("Yes")
    else:
        print("No")


C#




using System;
 
public class MainClass
{
    // Function to check whether a number
    // can be represented as the difference
    // of two consecutive cubes
    public static bool DiffCube(int N)
    {
        // Iterate over the possible values of i
        for (int i = 0; i <= 100000; i++)
        {
            int lo = i + 1, hi = 100000, mid;
 
            // Binary search for j
            while (lo <= hi)
            {
                mid = lo + (hi - lo) / 2;
 
                // Check if the difference is N
                if (Math.Pow(mid, 3) - Math.Pow(i, 3) == N)
                {
                    Console.WriteLine($"{i} {mid}");
                    return true;
                }
 
                // If the difference is less than N,
                // move the left pointer
                if (Math.Pow(mid, 3) - Math.Pow(i, 3) < N)
                    lo = mid + 1;
                // If the difference is greater than N,
                // move the right pointer
                else
                    hi = mid - 1;
            }
        }
 
        // If no such pair is found, return false
        return false;
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
        // Given Number N
        int N = 19;
        if (DiffCube(N))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }
}


Javascript




// Function to check whether a number
// can be represented as difference
// of two consecutive cubes
function diffCube(N) {
     
    // Iterate over the possible values of i
    for (let i = 0; i <= 100000; i++) {
        let lo = i + 1, hi = 100000, mid;
         
        // Binary search for j
        while (lo <= hi) {
            mid = lo + Math.floor((hi - lo) / 2);
             
            // Check if the difference is N
            if (Math.pow(mid, 3) - Math.pow(i, 3) === N) {
                console.log(i + " " + mid);
                return true;
            }
 
            // If the difference is less than N,
            // move the left pointer
            if (Math.pow(mid, 3) - Math.pow(i, 3) < N)
                lo = mid + 1;
            // If the difference is greater than N,
            // move the right pointer
            else
                hi = mid - 1;
        }
    }
    // If no such pair is found, return false
    return false;
}
 
// Driver Code
let N = 19;
if (diffCube(N))
    console.log("Yes");
else
    console.log("No");


Output

2 3
Yes


Time Complexity: O(N log^2(N)), where N is the given input number
Auxiliary Space: O(1)



Previous Article
Next Article

Similar Reads

Check if a number can be represented as sum of two consecutive perfect cubes
Given an integer N, the task is to check if this number can be represented as the sum of two consecutive perfect cubes or not. Examples: Input: N = 35Output: YesExplanation:Since, 35 = 23 + 33, therefore the required answer is Yes. Input: N = 14Output: No Naive Approach: The simplest approach to solve the problem is to iterate from 1 to cube root o
7 min read
Check if a number can be represented as difference of two positive perfect cubes
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: NoApp
16 min read
Check if a number can be represented as sum of two positive perfect cubes
Given an integer N, the task is to check if N can be represented as the sum of two positive perfect cubes or not. Examples: Input: N = 28Output: YesExplanation: Since, 28 = 27 + 1 = 33 + 13.Therefore, the required answer is Yes Input: N = 34Output: No Approach: The idea is to store the perfect cubes of all numbers from 1 to cubic root of N in a Map
16 min read
Check if a number can be represented as product of two positive perfect cubes
Given a positive integer N, the task is to check if the given number N can be represented as the product of two positive perfect cubes or not. If it is possible, then print "Yes". Otherwise, print "No". Examples: Input: N = 216Output: YesExplanation:The given number N(= 216) can be represented as 8 * 27 = 23 * 33.Therefore, print Yes. Input: N = 10
11 min read
Check whether a number can be represented as difference of two squares
Given a number N, the task is to check if this number can be represented as the difference of two perfect squares or not. Examples: Input: N = 3 Output: Yes Explanation: 22 - 11 = 3 Input: N = 10 Output: No Approach: The idea is that all the numbers can be represented as the difference of two squares except the numbers which yield the remainder of
6 min read
Check whether a number can be represented by sum of two squares
We have number n. We need to find whether number n can be represented by the sum of two squares. Examples : Input : n = 17 Output : Yes 4^2 + 1^2 = 17 Input : n = 169 Output : Yes 5^2 + 12^2 = 169 Input : n = 24 Output : No Brute-force approach - O(n) We use two for loops running till the square root of n and each time we find whether the sum of th
19 min read
Check whether a number can be represented by the product of two squares
Given an integer n, our task is to check whether number n can be represented by the product of two squares. If it is possible then print "yes" otherwise print "no".Examples : Input: n = 144 Output: Yes Explanation: The given number 144 can be represented as 22 * 62 = 144. Input: n = 25 Output: No Explanation: The given number 25 cannot be represent
7 min read
Check if N can be represented as sum of squares of two consecutive integers
Given an integer N, the task is to check whether N can be represented as a sum of squares of two consecutive integers or not. Examples: Input: N = 5 Output: Yes Explanation: The integer 5 = 12 + 22 where 1 and 2 are consecutive numbers. Input: 13 Output: Yes Explanation: 13 = 22 + 32 Approach: This equation can be represented as: =&gt; [Tex]N = K^{
6 min read
Check whether a number can be represented as sum of K distinct positive integers
Given two integers N and K, the task is to check whether N can be represented as sum of K distinct positive integers. Examples: Input: N = 12, K = 4 Output: Yes N = 1 + 2 + 4 + 5 = 12 (12 as sum of 4 distinct integers) Input: N = 8, K = 4 Output: No Recommended: Please try your approach on {IDE} first, before moving on to the solution.Approach: Con
10 min read
Check whether X can be represented in the form of (2n - 1) / 3
Given an integer X, the task is to check whether X can be represented in the form of X = (2n - 1) / 3 for some value of n, Where it is necessary for X to be prime. Examples: Input: X = 5Output: YesExplanation: X is a prime number and (24 - 1) / 3 = (16 - 1) / 3 = 15 / 3 = 5. So, it is valid. Input: X = 2Output: No Approach: This can be solved with
6 min read