GeeksforGeeks App
Open App Browser
Continue

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

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 ``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

 ``

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 ``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``    ``a    ``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"``)`

Output

```2 3
Yes```

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

My Personal Notes arrow_drop_up
{"ft_lang_label":"__label__en","ft_lang_prob":0.6663063,"math_prob":0.99083793,"size":10264,"snap":"2023-14-2023-23","text_gpt3_token_len":3174,"char_repetition_ratio":0.13859649,"word_repetition_ratio":0.44243267,"special_character_ratio":0.35736555,"punctuation_ratio":0.11968735,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9998425,"pos_list":[0,1,2,3,4],"im_url_duplicate_count":[null,null,null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2023-05-30T21:21:33Z\",\"WARC-Record-ID\":\"<urn:uuid:7335db13-7a9e-4fdd-8461-51d89622a2f9>\",\"Content-Length\":\"299739\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:8dca71b7-a29e-475b-b507-a384f05e26bf>\",\"WARC-Concurrent-To\":\"<urn:uuid:c241c9ff-c19f-4f8f-9150-1f192b211ef9>\",\"WARC-IP-Address\":\"23.213.158.90\",\"WARC-Target-URI\":\"https://www.geeksforgeeks.org/check-whether-a-number-can-be-represented-as-difference-of-two-consecutive-cubes/?type=article&id=446828\",\"WARC-Payload-Digest\":\"sha1:ZYKM3JBWIDAGSSOH6IXQ7HRXBWJ3ETPW\",\"WARC-Block-Digest\":\"sha1:NRBW7J4SE5RLGY4A56IWLO543E6F25HH\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2023/CC-MAIN-2023-23/CC-MAIN-2023-23_segments_1685224646144.69_warc_CC-MAIN-20230530194919-20230530224919-00291.warc.gz\"}"}