Last Updated: 29 Dec, 2020

Cube Sum Pairs

Easy
Asked in companies
BarclaysFreshworksAdobe

Problem statement

You are given a positive integer N, and you have to find the number of ways to represent N as a sum of cubes of two integers(let’s say A and B), such that:

N = A^3 + B^3.

Note:

1. A should be greater than or equal to one (A>=1).
2. B should be greater than or equal to zero (B>=0).
3. (A, B) and (B, A) should be considered different solutions, if A is not equal to B, i.e (A, B) and (B, A) will not be distinct if A=B.
Input Format:
The first line of the input contains an integer T denoting the number of test cases.

The first and only line of each test case consists of a single positive integer N.
Output Format:
For each test case, print an integer that denotes the count of the number of ways of representing N as a sum of cubes of 2 integers (A and B) in a separate line.
Note:
You don't have to print anything, it has already been taken care of. Just Implement the given function.
Constraints:
1 <= T <= 10^3
1 <= N <= 10^8
Time Limit: 1 sec.

Approaches

01 Approach

  1. Maintain a counter which will count possible pairs (A, B).
  2. Iterate over all possible ‘A’ values.
    • Possible ‘A’ values are in the range 1 to N.
  3. For each ‘A’ value iterate over all possible values of ‘B’
    • Possible ‘B’ values are in the range 0 to N.
  4. If ‘A’^3 + ‘B’^3 comes to be N, then increment the counter.

02 Approach

  1. Maintain a counter which will count the pairs (A, B).
  2. Iterate over all possible values of ‘A’.
    • Possible values of ‘A’ are in the range 1 to N.
  3. For each value, ‘A’ find the value of N - A^3.
  4. Check if N - A^3 is positive as well as a perfect cube.
  5. To check if N - A^3 is a perfect cube or not, follow the following steps:
    • Find the cube root of N - A^3 and take the floor value of this cube root.
    • Only If the cube of this floored cube root comes out to be equal to N - A^3, then it is a perfect cube.
  6. If N - A^3 is a perfect cube then we can get a ‘B’ value which is nothing but cubeRoot(N-A^3) and increment the counter.

03 Approach

  1. Maintain a counter which will count the pairs (A, B).
  2. Iterate over all valid values of ‘A’.
    • Possible values of ‘A’ are in the range 1 to N.
    • But out of these values in range 1 to cubeRoot(N), will take us to a valid Pair(A, B).
    • Values of ‘A’ above cubeRoot(N) will make N - A^3 negative.
  3. For each valid value ‘A’ find the value of N - A^3.
  4. Check if N - A^3 is positive as well as a perfect cube.
  5. To check if N - A^3 is a perfect cube or not, follow the following steps:
    • Find the cube root of N - A^3 and take the floor value of this cube root.
    • Only If the cube of this floored cube root comes out to be equal to N - A^3, then it is a perfect cube.
  6. If N - A^3 is a perfect cube then we can get a ‘B’ value which is nothing but cubeRoot(N-A^3) and increment the counter.