# Find Cube Pairs - (A n^(2/3) Solution) in C++

C++Server Side ProgrammingProgramming

A number is given. We have to find two pairs, that can represent the number as sum of two cubes. So we have to find two pairs (a, b) and (c, d) such that the given number n can be expressed as n = a3 + b3 = c3 + d3

The idea is simple. Here every number a, b, c and d are all less than n1/3. For every distinct pair (x, y) formed by number less than n1/3, if their sum (x3 + y3) is equal to the given number, we store them into hash table with the sum value as key, then if the same sum comes again, them simply print each pair

## Algorithm

getPairs(n):
begin
cube_root := cube root of n
map as int type key and pair type value
for i in range 1 to cube_root, do
for j in range i + 1 to cube_root, do
sum = i3 + j3
if sum is not same as n, then skip next part, go to second iteration
if sum is present into map, then print pair, and (i, j),
else insert (i,j) with corresponding sum into the map
done
done
end

## Example

Live Demo

#include <iostream>
#include <cmath>
#include <map>
using namespace std;
int getPairs(int n){
int cube_root = pow(n, 1.0/3.0);
map<int, pair<int, int> > my_map;
for(int i = 1; i<cube_root; i++){
for(int j = i + 1; j<= cube_root; j++){
int sum = i*i*i + j*j*j;
if(sum != n)
continue;
if(my_map.find(sum) != my_map.end()){
cout << "(" << my_map[sum].first << ", " << my_map[sum].second << ") and (" << i << ", " << j << ")" << endl;
}else{
my_map[sum] = make_pair(i, j);
}
}
}
}
int main() {
int n = 13832;
getPairs(n);
}

## Output

(2, 24) and (18, 20)
Published on 25-Sep-2019 13:04:44