VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-pairs-a-b-whose-sum-of-cubes-is-n-a3-b3-n/

⇱ Pair Cube Count - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Pair Cube Count

Last Updated : 19 Mar, 2025

Given n, count all 'a' and 'b' that satisfy the condition a^3 + b^3 = n. Where (a, b) and (b, a) are considered two different pairs

Examples:

Input: n = 9
Output: 2
Explanation: 1^3 + 2^3 = 9 and 2^3 + 1^3 = 9

Input: n = 28
Output: 2
Explanation: 1^3 + 3^3 = 28 and 3^3 + 1^3 = 28

[Naive Approach] Using Nested Loops - O(n^2) time and O(1) space

The approach uses a nested loop to check all pairs (a, b) where a3+b3=n. If the condition holds, the count is incremented.


Output
2

[Expected Approach] Finding different pairs - O(n1/3) time and O(1) space

While traversing numbers from 1 to the cube root of n, Subtract the cube of the current number from n and check if their difference is a perfect cube.


Output
2


Comment
Article Tags: