Find elements in given Array that are a factor of sum of remaining elements - GeeksforGeeks

10 Feb, 2022
Given an array A[] of size N, the task is to find the elements in the array which are factors of the sum of the remaining element. So just select an element from an array and take the sum of the remaining elements and check whether the sum is perfectly divisible by the selected element or not. If it is divisible then return the element.
Examples:
Input: A[] = {2, 4, 6, 8, 10, 12, 14}Output: [2, 4, 8, 14]Explanation: 1. Take sum for remaining element except selected one.2. For element 2, sum of remaining element is 4+6+8+10+12+14=54 3. Similarly for complete array: [54, 52, 50, 48, 46, 44, 42]3. 54/2, 52/4, 48/8, 42/14 are perfectly divisible so resultant elements are [2, 4, 8, 14]
Input: A[]= {3, 6, 8, 10, 7, 15}Output: [7]
Naive Approach: Take the sum of all elements from the array. Now subtract each element one by one from sum and append it to new array p[]. Divide each sum by the corresponding index element from a given array and append it to new array q[ ]. Multiply the corresponding element from array A[] and array q[] and compare it with similar indexed elements from array p[]. If they are equal then append it to a new array z[ ]. If no such element is found return -1.
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// c++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find elementvector<int> Factor(vector<int> A){   // Sum of all element  int s = 0;   for (int i = 0; i < A.size(); i++)  {    s += A[i];  }   // Subtract each element from sum  vector<int> p;  for (int i : A)    p.push_back(s - i);   // Divide corresponding element  // from array p and l  vector<int> q;  for (int i = 0; i < A.size(); i++)    q.push_back(p[i] / A[i]);   // Check sum is divisible by  // corresponding element or not  vector<int> z;  for (int i = 0; i < q.size(); i++)  {     // First we divided element now multiple    // to check perfect divisibility of element    if (q[i] * A[i] == p[i])      z.push_back(A[i]);  }   return z;} // Driver codeint main(){  vector<int> A = {2, 4, 6, 8, 10, 12, 14};   // Calling function  vector<int> b = Factor(A);   // Print required array  for (auto i : b)  {    cout << i << " ";  }} // This code is contributed by amreshkumar3.
// Java program for the above approachimport java.util.ArrayList; class GFG{ // Function to find elementstatic ArrayList<Integer> Factor(int[] A){         // Sum of all element    int s = 0;     for(int i = 0; i < A.length; i++)    {        s += A[i];    }     // Subtract each element from sum    ArrayList<Integer> p = new ArrayList<>();    for(int i : A)        p.add(s - i);     // Divide corresponding element    // from array p and l    ArrayList<Integer> q = new ArrayList<Integer>();    for(int i = 0; i < A.length; i++)        q.add((int) Math.floor(p.get(i) / A[i]));     // Check sum is divisible by    // corresponding element or not    ArrayList<Integer> z = new ArrayList<Integer>();    for(int i = 0; i < q.size(); i++)    {                 // First we divided element now multiple        // to check perfect divisibility of element        if (q.get(i) * A[i] == p.get(i))            z.add(A[i]);    }         // If no such element found return -1    if (z.size() == 0)        return new ArrayList<Integer>();             return z;} // Driver codepublic static void main(String args[]){    int[] A = { 2, 4, 6, 8, 10, 12, 14 };     // Calling function    ArrayList<Integer> b = Factor(A);     // Print required array    System.out.println(b);}} // This code is contributed by gfgking
# Python program for the above approach # Function to find elementdef Factor(A):       # Sum of all element    s = sum(A)         # Subtract each element from sum    p =[]    for i in A:        p.append(s-i)     # Divide corresponding element    # from array p and l    q =[]    for i in range(len(A)):        q.append(p[i]//A[i])     # Check sum is divisible by    # corresponding element or not    z =[]    for i in range(len(q)):                 # First we divided element now multiple        # to check perfect divisibility of element        if q[i]*A[i]== p[i]:            z.append(A[i])                 # If no such element found return -1    if len(z)== 0:      return -1    return z A = [2, 4, 6, 8, 10, 12, 14] # Calling functionb = Factor(A) # Print required arrayprint(b)
// C# program for the above approachusing System;using System.Collections.Generic; public class GFG{   // Function to find element  static List<int> Factor(int[] A)  {     // Sum of all element    int s = 0;     for(int i = 0; i < A.Length; i++)    {      s += A[i];    }     // Subtract each element from sum    List<int> p = new List<int>();    foreach(int i in A)      p.Add(s - i);     // Divide corresponding element    // from array p and l    List<int> q = new List<int>();    for(int i = 0; i < A.Length; i++)      q.Add((int) Math.Floor((double)p[i] / A[i]));     // Check sum is divisible by    // corresponding element or not    List<int> z = new List<int>();    for(int i = 0; i < q.Count; i++)    {       // First we divided element now multiple      // to check perfect divisibility of element      if (q[i] * A[i] == p[i])        z.Add(A[i]);    }     // If no such element found return -1    if (z.Count == 0)      return new List<int>();     return z;  }   // Driver code  public static void Main(String []args)  {    int[] A = { 2, 4, 6, 8, 10, 12, 14 };     // Calling function    List<int> b = Factor(A);     // Print required array    foreach(int i in b)      Console.Write(i+", ");  }}  // This code is contributed by 29AjayKumar
  <script>      // JavaScript code for the above approach       // Function to find element      function Factor(A) {           // Sum of all element          let s = 0;           for (let i = 0; i < A.length; i++) {              s += A[i]          }           // Subtract each element from sum          p = []          for (i of A)              p.push(s - i)           // Divide corresponding element          // from array p and l          q = []          for (i = 0; i < A.length; i++)              q.push(Math.floor(p[i] / A[i]))           // Check sum is divisible by          // corresponding element or not          z = []          for (let i = 0; i < q.length; i++) {               // First we divided element now multiple              // to check perfect divisibility of element              if (q[i] * A[i] == p[i])                  z.push(A[i])          }          // If no such element found return -1          if (z.length == 0)              return -1          return z      }      A = [2, 4, 6, 8, 10, 12, 14]       // Calling function      b = Factor(A)       // Print required array      document.write(b) // This code is contributed by Potta Lokesh  </script>
[2, 4, 8, 14]
Time Complexity: O(N)Auxiliary Space: O(N)
Efficient Approach: In this approach, there is no need to use multiple loops and multiple arrays. so space complexity and time complexity will be decreased. In this, all the subtraction, division, multiplication operation are performed in a single loop. Follow the steps below to solve the problem:
Initialize the variable s as the sum of the array A[].
Initialize the array z[] to store the result.
Iterate over the range [0, len(A)) using the variables i and perform the following tasks:Initialize the variable a as s-l[i], b as a/A[i].If b*A[i] equals a then append A[i] into z[].
Initialize the variable a as s-l[i], b as a/A[i].
If b*A[i] equals a then append A[i] into z[].
After performing the above steps, print -1 if the resultant array is empty, else print the elements of the array z[] as the answer.
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find sum of all elements of an arrayint sum(vector<int>& A){  int res = 0;  for (auto it : A)    res += it;  return res;} // Function to find elementvector<int> Factor(vector<int>& A){   // Sum of all element  int s = sum(A);  vector<int> z;   // Loop to find the factors of sum.  for (int i = 0; i < A.size(); ++i) {     // a is sum of remaining elements.    int a = s - A[i];     // b is integer value or factor of b.    int b = a / A[i];     // Check the divisibility    if (b * A[i] == a)      z.push_back(A[i]);  }   // If no element found return -1  if (z.size() == 0)    return { -1 };   return z;} // Drive Code int main(){  vector<int> A = { 2, 4, 6, 8, 10, 12, 14 };   // Calling function  vector<int> b = Factor(A);   // Print resultant element  for (auto it : b)    cout << it << " ";   return 0;} // This code is contributed by rakeshsahni
// Java program for the above approachimport java.util.*;class GFG{   // Function to find sum of all elements of an array  static int sum(int[] A)  {    int res = 0;    for (int i = 0; i < A.length; i++) {      res += A[i];    }    return res;  }   // Function to find element  static ArrayList<Integer> Factor(int[] A)  {     // Sum of all element    int s = sum(A);    ArrayList<Integer> z = new ArrayList<Integer>();     // Loop to find the factors of sum.    for (int i = 0; i < A.length; ++i) {       // a is sum of remaining elements.      int a = s - A[i];       // b is integer value or factor of b.      int b = a / A[i];       // Check the divisibility      if (b * A[i] == a){        z.add(A[i]);      }    }     // If no element found return -1    if (z.size() == 0){      ArrayList<Integer> l1 = new ArrayList<Integer>();      l1.add(-1);      return l1;    }     return z;  }   // Drive Code  public static void main (String[] args)  {    int A[] = new int[] { 2, 4, 6, 8, 10, 12, 14 };     // Calling function    ArrayList<Integer> b = Factor(A);     // Print resultant element    System.out.println(b);  }} // This code is contributed by Shubham Singh
# Python program for the above approach # Function to find elementdef Factor(A):     # Sum of all element    s = sum(A)    z = []     # Loop to find the factors of sum.    for i in range(len(A)):         # a is sum of remaining elements.        a = s-A[i]         # b is integer value or factor of b.        b = a//A[i]         # Check the divisibility        if b * A[i] == a:            z.append(A[i])     # If no element found return -1    if len(z) == 0:        return -1     return z  A = [2, 4, 6, 8, 10, 12, 14] # Calling functionb = Factor(A) # Print resultant elementprint(b)
// C# program for the above approachusing System;using System.Collections.Generic;class GFG {   // Function to find sum of all elements of an array  static int sum(List<int> A)  {    int res = 0;    foreach(int it in A) res += it;    return res;  }   // Function to find element  static List<int> Factor(List<int> A)  {     // Sum of all element    int s = sum(A);    List<int> z = new List<int>();     // Loop to find the factors of sum.    for (int i = 0; i < A.Count; ++i) {       // a is sum of remaining elements.      int a = s - A[i];       // b is integer value or factor of b.      int b = a / A[i];       // Check the divisibility      if (b * A[i] == a)        z.Add(A[i]);    }     // If no element found return -1    if (z.Count == 0)      return new List<int>() { -1 };     return z;  }   // Drive Code   public static void Main()  {    List<int> A      = new List<int>() { 2, 4, 6, 8, 10, 12, 14 };     // Calling function    List<int> b = Factor(A);     // Print resultant element    Console.Write("[ ");    int it;    for (it = 0; it < b.Count - 1; it++) {      Console.Write(b[it] + ", ");    }    Console.Write(b[it] + " ]");  }} // This code is contributed by ukasp.
<script>// JavaScript program for the above approach // Function to find sum of all elements of an arrayfunction sum(A){  var res = 0;  for (var it of A){    res += parseInt(it);}  return res;} // Function to find elementfunction Factor(A){   // Sum of all element  var s = sum(A);     var z =[];   // Loop to find the factors of sum.  for (var i = 0; i < A.length; ++i) {     // a is sum of remaining elements.    var a = s - A[i];     // b is integer value or factor of b.    var b = parseInt(a / A[i]);     // Check the divisibility    if (b * A[i] == a)      z.push(A[i]);  }   // If no element found return -1  if (z.length == 0)    return [ -1 ];   return z;} // Drive CodeA = [ 2, 4, 6, 8, 10, 12, 14 ]; // Calling functionb = Factor(A); // Print resultant elementfor (var it of b)document.write(it + " "); //This code is contributed by Shubham Singh</script>
[2, 4, 8, 14]
Time Complexity: O(N)Auxiliary Space: O(1)
lokeshpotta20
rakeshsahni
ukasp
gfgking
29AjayKumar
SHUBHAMSINGH10
amreshkumar3
simmytarika5
surinderdawra388
Algo-Geek 2021
factor
Algo Geek
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count of operation required to water all the plants
Encode given String by inserting in Matrix column-wise and printing it row-wise
Lexicographically smallest string formed by concatenating any prefix and its mirrored form
Check if the given string is valid English word or not
Bit Manipulation technique to replace boolean arrays of fixed size less than 64
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7