Count of pairs in an Array whose sum is a Perfect Cube

Given an array arr of distinct elements of size N, the task is to find the total number of pairs in the array whose sum is a perfect cube.

Examples:

Input: arr[] = {2, 3, 6, 9, 10, 20}
Output: 1
Only possible pair is (2, 6)



Input: arr[] = {9, 2, 5, 1}
Output: 0

Naive Approach: Use nested loops and check every possible pair for whether their sum is a perfect cube or not. This technique is not effective when the length of the array is very large.

Efficient Approach:

  • Store all the elements of the array in a HashSet and save the sum of the maximum two elements in a variable named max.
  • It is clear that the sum of any two elements from the array will not exceed max. So, find all the perfect cubes which are max and save it in an ArrayList named perfectcubes.
  • Now for every element in the array say arr[i] and for every perfect cube saved in perfectcubes, check whether perfectcubes.get(i) – arr[i] exists in nums or not i.e. if there is any element in the original array that when added with the currently chosen element gives any perfect cube from the list.
  • If the above condition is satisfied, increment the count variable.
  • Print the value of count in the end.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach 
#include<bits/stdc++.h>
#include<vector>
using namespace std;
  
// Function to return an ArrayList containing 
// all the perfect cubes upto n 
vector<int> getPerfectcubes(int n)
{
  
    vector<int>perfectcubes; 
    int current = 1; 
    int i = 1; 
  
    // while current perfect cube is 
    // less than or equal to n 
    while (current <= n)
    {
        perfectcubes.push_back(current); 
        i += 1; 
        current = int(pow(i, 3)); 
    }
    return perfectcubes; 
  
// Function to print the sum of maximum 
// two elements from the array 
int maxPairSum(int arr[],int n)
{
  
    int max = 0; 
    int secondMax = 0; 
    if (arr[0] > arr[1])
    {
        max = arr[0]; 
        secondMax = arr[1]; 
    }
    else
    {
        max = arr[1]; 
        secondMax = arr[0]; 
    }
    for (int i = 2; i < n; i++)
    {
        if (arr[i] > max)
        {
            secondMax = max; 
            max = arr[i]; 
        }
        else if (arr[i] > secondMax)
            secondMax = arr[i]; 
    }
    return (max + secondMax); 
}
  
// Function to return the count of numbers that 
// when added with n give a perfect cube 
int countPairsWith(int n, vector<int> perfectcubes, vector<int> nums)
{
  
    int count = 0; 
    int len=perfectcubes.size();
    for (int i = 0; i < len; i++)
    {
        int temp = perfectcubes[i] - n; 
  
        // temp > n is checked so that pairs 
        // (x, y) and (y, x) don't get counted twice 
        if (temp > n)
        {
            for(auto j=nums.begin();j!=nums.end();j++)
            {
                if((*j)==temp)
                    count += 1; 
            }
        }
    
    return count; 
}
  
// Function to count the pairs whose 
// sum is a perfect cube 
int countPairs(int arr[],int n)
{
  
    // Sum of the maximum two elements 
    // from the array 
    int max = maxPairSum(arr,n); 
  
    // List of perfect cubes upto max 
    vector<int>perfectcubes = getPerfectcubes(max); 
  
    // Contains all the array elements 
    vector<int>nums; 
    for (int i = 0 ; i < n; i++) 
        nums.push_back(arr[i]);
  
    int count = 0; 
    for (int i = 0; i < n; i++)
    {
  
        // Add count of the elements that when 
        // added with arr[i] give a perfect cube 
        count += countPairsWith(arr[i], perfectcubes, nums); 
    }
    return count; 
  
}
  
// Driver code 
int main()
{
    int arr[] = { 2, 6, 18, 9, 999, 1 }; 
    int n=sizeof(arr)/sizeof(arr[0]);
    cout<<(countPairs(arr,n)); 
      
}
  
// This code is contributed by chitranayal

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the approach
import java.util.*;
  
class GFG 
{
  
    // Function to return an ArrayList containing
    // all the perfect cubes upto n
    static List<Integer> getPerfectcubes(int n) {
  
        List<Integer> perfectcubes = new ArrayList<Integer>();
        int current = 1;
        int i = 1;
  
        // while current perfect cube is
        // less than or equal to n
        while (current <= n) {
            perfectcubes.add(current);
            i += 1;
            current = (int) (Math.pow(i, 3));
        }
        return perfectcubes;
    }
  
    // Function to print the sum of maximum
    // two elements from the array
    static int maxPairSum(int[] arr) {
  
        int n = arr.length;
        int max = 0;
        int secondMax = 0;
        if (arr[0] > arr[1]) {
            max = arr[0];
            secondMax = arr[1];
        } else {
            max = arr[1];
            secondMax = arr[0];
        }
        for (int i = 2; i < n; i++) {
            if (arr[i] > max) {
                secondMax = max;
                max = arr[i];
            } else if (arr[i] > secondMax) {
                secondMax = arr[i];
            }
        }
        return (max + secondMax);
    }
  
    // Function to return the count of numbers that
    // when added with n give a perfect cube
    static int countPairsWith(int n, List<Integer> 
            perfectcubes, List<Integer> nums) {
  
        int count = 0;
        for (int i = 0; i < perfectcubes.size(); i++) {
            int temp = perfectcubes.get(i) - n;
  
            // temp > n is checked so that pairs
            // (x, y) and (y, x) don't get counted twice
            if (temp > n && (nums.contains(temp)))
                count += 1;
        }
        return count;
    }
  
    // Function to count the pairs whose
    // sum is a perfect cube
    static int countPairs(int[] arr) {
  
        int n = arr.length;
  
        // Sum of the maximum two elements
        // from the array
        int max = maxPairSum(arr);
  
        // List of perfect cubes upto max
        List<Integer> perfectcubes = getPerfectcubes(max);
  
        // Contains all the array elements
        List<Integer> nums = new ArrayList<Integer>();
        for (int i = 0; i < n; i++) {
            nums.add(arr[i]);
        }
        int count = 0;
        for (int i = 0; i < n; i++) {
  
            // Add count of the elements that when
            // added with arr[i] give a perfect cube
            count += countPairsWith(arr[i], perfectcubes, nums);
        }
        return count;
    }
  
    // Driver code
    public static void main(String[] agrs) {
        int[] arr = { 2, 6, 18, 9, 999, 1 };
        System.out.print(countPairs(arr));
    }
}
  
// This code is contributed by Rajput-Ji

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation of the approach 
  
# Function to return an ArrayList containing 
# all the perfect cubes upto n 
def getPerfectcubes(n): 
  
    perfectcubes = []; 
    current = 1
    i = 1
  
    # while current perfect cube is 
    # less than or equal to n 
    while (current <= n): 
        perfectcubes.append(current); 
        i += 1
        current = int(pow(i, 3)); 
  
    return perfectcubes; 
  
# Function to print the sum of maximum 
# two elements from the array 
def maxPairSum(arr): 
  
    n = len(arr); 
    max = 0
    secondMax = 0
    if (arr[0] > arr[1]): 
        max = arr[0]; 
        secondMax = arr[1]; 
    else
        max = arr[1]; 
        secondMax = arr[0]; 
  
    for i in range(2, n): 
        if (arr[i] > max): 
            secondMax = max
            max = arr[i]; 
        elif (arr[i] > secondMax): 
            secondMax = arr[i]; 
  
    return (max + secondMax); 
  
# Function to return the count of numbers that 
# when added with n give a perfect cube 
def countPairsWith(n, perfectcubes, nums): 
  
    count = 0
    for i in range(len(perfectcubes)): 
        temp = perfectcubes[i] - n; 
  
        # temp > n is checked so that pairs 
        # (x, y) and (y, x) don't get counted twice 
        if (temp > n and (temp in nums)): 
            count += 1
  
    return count; 
  
# Function to count the pairs whose 
# sum is a perfect cube 
def countPairs(arr): 
  
    n = len(arr); 
  
    # Sum of the maximum two elements 
    # from the array 
    max = maxPairSum(arr); 
  
    # List of perfect cubes upto max 
    perfectcubes = getPerfectcubes(max); 
  
    # Contains all the array elements 
    nums = []; 
    for i in range(n): 
        nums.append(arr[i]); 
  
    count = 0
    for i in range(n): 
  
        # Add count of the elements that when 
        # added with arr[i] give a perfect cube 
        count += countPairsWith(arr[i], 
                perfectcubes, nums); 
    return count; 
  
# Driver code 
arr = [ 2, 6, 18, 9, 999, 1 ]; 
print(countPairs(arr)); 

chevron_right


Output:

3



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : Rajput-Ji, chitranayal