Sum of elements whose square root is present in the array

Given an array arr[], the task is to find the sum of all those elements from the given array whose square root is present in the same array.

Examples:

Input: arr[] = {1, 2, 3, 4, 6, 9, 10}
Output: 13
4 and 9 are the only numbers whose square roots 2 and 3 are present in the array

Input: arr[] = {4, 2, 36, 6, 10, 100}
Output: 140

Naive Approach: To find the sum of elements whose square root is present in the given array, check for square root of every element by iterating from arr[0] to arr[n] which will do the job but in O(n*n) complexity.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to find the sum of all the elements
// from the array whose square root is present
// in the same array
  
#include<bits/stdc++.h>
using namespace std;
  
    // Function to return the required sum
int getSum(int arr[], int n)
    {
  
        int sum = 0;
  
        for (int i = 0; i < n; i++) {
            double sqrtCurrent = sqrt(arr[i]);
  
            for (int j = 0; j < n; j++) {
                double x = arr[j];
  
                // If sqrtCurrent is present in array
                if (x == sqrtCurrent) {
                    sum += (sqrtCurrent * sqrtCurrent);
                    break;
                }
            }
        }
  
        return sum;
    }
  
    // Driver code
    int main()
    {
        int arr[] = { 2, 4, 5, 6, 7, 8, 9, 3 };
        int n = sizeof(arr)/sizeof(arr[0]);
        cout<<(getSum(arr, n));
    }
// This code is contributed by 
// Surendra_Gangwar

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to find the sum of all the elements
// from the array whose square root is present
// in the same array
public class GFG {
    // Function to return the required sum
    public static int getSum(int arr[], int n)
    {
  
        int sum = 0;
  
        for (int i = 0; i < n; i++) {
            double sqrtCurrent = Math.sqrt(arr[i]);
  
            for (int j = 0; j < n; j++) {
                double x = arr[j];
  
                // If sqrtCurrent is present in array
                if (x == sqrtCurrent) {
                    sum += (sqrtCurrent * sqrtCurrent);
                    break;
                }
            }
        }
  
        return sum;
    }
  
    // Driver code
    public static void main(String args[])
    {
        int arr[] = { 2, 4, 5, 6, 7, 8, 9, 3 };
        int n = arr.length;
        System.out.println(getSum(arr, n));
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to find the sum of
# all the elements from the array 
# whose square root is present in
# the same array
import math 
  
# Function to return the required sum
def getSum(arr, n):
    sum = 0
    for i in range(0, n):
        sqrtCurrent = math.sqrt(arr[i])
        for j in range(0, n):
            x = arr[j]
              
            # If sqrtCurrent is present in array
            if (x == sqrtCurrent):
                sum += (sqrtCurrent * 
                        sqrtCurrent)
                break
    return int(sum)
  
# Driver code
if __name__ == '__main__':
  
    arr = [ 2, 4, 5, 6, 7, 8, 9, 3]
    n = len(arr)
    print(getSum(arr, n))
      
# This code is contributed 
# by 29AjayKumar

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find the sum of all the elements 
// from the array whose square root is present 
// in the same array 
using System ;
  
public class GFG {
      
    // Function to return the required sum 
    public static float getSum(int []arr, int n) 
    
  
        float sum = 0; 
  
        for (int i = 0; i < n; i++) { 
            float sqrtCurrent = (float)Math.Sqrt(arr[i]); 
  
            for (int j = 0; j < n; j++) { 
                float x = (float)arr[j]; 
  
                // If sqrtCurrent is present in array 
                if (x == sqrtCurrent) { 
                    sum += (sqrtCurrent * sqrtCurrent); 
                    break
                
            
        
  
        return sum; 
    
  
    // Driver code 
    public static void Main() 
    
        int []arr = { 2, 4, 5, 6, 7, 8, 9, 3 }; 
        int n = arr.Length; 
        Console.WriteLine(getSum(arr, n)); 
    
    // This code is contributed by Ryuga

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to find the sum of all 
// the elements from the array whose 
// square root is present in the same array
  
// Function to return the required sum
function getSum(&$arr, $n)
{
    $sum = 0;
  
    for ($i = 0; $i < $n; $i++) 
    {
        $sqrtCurrent = sqrt($arr[$i]);
  
        for ($j = 0; $j < $n; $j++) 
        {
            $x = $arr[$j];
  
            // If sqrtCurrent is present in array
            if ($x == $sqrtCurrent)
            {
                $sum += ($sqrtCurrent * $sqrtCurrent);
                break;
            }
        }
    }
  
    return $sum;
}
  
// Driver code
$arr = array(2, 4, 5, 6, 7, 8, 9, 3);
$n = sizeof($arr);
echo (getSum($arr, $n));
      
// This code is contributed 
// by Shivi_Aggarwal
?>

chevron_right


Output:

13

Efficient Approach: We can create a HashSet of all the elements present in the array and than check for the square root of each element of the array in O(n) time.

Below is the implementation of the above approach:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to find the sum of all the elements
// from the array whose square root is present
// in the same array
  
import java.util.*;
public class GFG {
  
    // Function to return the required sum
    public static int getSum(int arr[], int n)
    {
  
        int i, sum = 0;
  
        // Initialization of hash map
        Set<Integer> hashSet = new HashSet<>();
  
        // Store each element in the hash map
        for (i = 0; i < n; i++)
            hashSet.add(arr[i]);
  
        for (i = 0; i < n; i++) {
            double sqrtCurrent = Math.sqrt(arr[i]);
  
            // If sqrtCurrent is a decimal number
            if (Math.floor(sqrtCurrent) != Math.ceil(sqrtCurrent))
                continue;
  
            // If hash set contains sqrtCurrent
            if (hashSet.contains((int)sqrtCurrent)) {
                sum += (sqrtCurrent * sqrtCurrent);
            }
        }
  
        return sum;
    }
  
    // Driver code
    public static void main(String args[])
    {
        int arr[] = { 2, 4, 5, 6, 7, 8, 9, 3 };
        int n = arr.length;
        System.out.println(getSum(arr, n));
    }
}

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find the sum of all the elements 
// from the array whose square root is present 
// in the same array 
using System;
using System.Collections.Generic; 
  
class GFG 
  
    // Function to return the required sum 
    public static int getSum(int []arr, int n) 
    
  
        int i, sum = 0; 
  
        // Initialization of hash map 
        HashSet<int> hashSet = new HashSet<int>(); 
  
        // Store each element in the hash map 
        for (i = 0; i < n; i++) 
            hashSet.Add(arr[i]); 
  
        for (i = 0; i < n; i++) 
        
            double sqrtCurrent = Math.Sqrt(arr[i]); 
  
            // If sqrtCurrent is a decimal number 
            if (Math.Floor(sqrtCurrent) != 
                Math.Ceiling(sqrtCurrent)) 
                continue
  
            // If hash set contains sqrtCurrent 
            if (hashSet.Contains((int)sqrtCurrent)) 
            
                sum += (int)(sqrtCurrent * sqrtCurrent); 
            
        
  
        return sum; 
    
  
    // Driver code 
    public static void Main(String []args) 
    
        int []arr = { 2, 4, 5, 6, 7, 8, 9, 3 }; 
        int n = arr.Length; 
        Console.WriteLine(getSum(arr, n)); 
    
  
// This code contributed by Rajput-Ji

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to find the sum of all the 
# elements from the array whose square 
# root is present in the same array
import math
  
# Function to return the required sum
def getSum(arr, n):
    sum = 0;
  
    # Initialization of hash map
    hashSet = set();
  
    # Store each element in the hash map
    for i in range(n):
        hashSet.add(arr[i]);
      
    for i in range(n):
      
        sqrtCurrent = math.sqrt(arr[i]);
  
        # If sqrtCurrent is a decimal number
        if (math.floor(sqrtCurrent) != math.ceil(sqrtCurrent)):
            continue;
  
        # If hash set contains sqrtCurrent
        if (int(sqrtCurrent) in hashSet):
            sum += int(sqrtCurrent * sqrtCurrent);
  
    return sum;
  
# Driver code
arr = [ 2, 4, 5, 6, 7, 8, 9, 3 ];
n = len(arr);
print(getSum(arr, n));
  
# This code is contributed by mits

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to find the sum of all the 
// elements from the array whose square 
// root is present in the same array
  
// Function to return the required sum
function getSum($arr, $n)
{
    $sum = 0;
  
    // Initialization of hash map
    $hashSet = array();
  
    // Store each element in the hash map
    for ($i = 0; $i < $n; $i++)
        array_push($hashSet, $arr[$i]);
          
    $hashSet = array_unique($hashSet);
      
    for ($i = 0; $i < $n; $i++)
    {
        $sqrtCurrent = sqrt($arr[$i]);
  
        // If sqrtCurrent is a decimal number
        if (floor($sqrtCurrent) != ceil($sqrtCurrent))
            continue;
  
        // If hash set contains sqrtCurrent
        if (in_array((int)$sqrtCurrent, $hashSet))
        {
            $sum += ($sqrtCurrent * $sqrtCurrent);
        }
    }
  
    return $sum;
}
  
// Driver code
$arr = array( 2, 4, 5, 6, 7, 8, 9, 3 );
$n = count($arr);
print(getSum($arr, $n));
  
// This code is contributed by mits
?>

chevron_right


Output:

13


My Personal Notes arrow_drop_up

Data science |Machine learning|Programming facebook -https//wwwfacebookcom/profilephpid=100002787011326

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.





Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.