Count array elements that divide the sum of all other elements in C++



We are given an array let’s say, arr[] of integer values and the task is to calculate the count of array elements that divides the sum of all other elements.

Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

For Example

Input − int arr_1[] = {9, 6, 3} Output − count is 3

Explanation − As the sum of elements 9+6 = 15 which is divisible by 3, sum of elements 9+3 =12 which is divisible by 6 and 6+3 = 9 which is divisible by 9. Therefore, count is 3.

Input − arr[] = {3, 10, 4, 6, 7} Output − count is 3

Explanation − As the sum of elements 10+4+6+7 = 27 which is divisible by 3, sum of elements 3+4+6+7 =20 which is divisible by 10 and 3+10+4+7 = 24 which is divisible by 6. Therefore, count is 3.

Approach used in the below program is as follows

  • Create an array let’s say, arr[]

  • Calculate the length of an array using the length() function that will return an integer value as per the elements in an array.

  • Take a temporary variable that will store the count of elements.

  • Start loop for i to 0 and i less than size of array

  • Inside the loop, set temporary variable let’s say temp to 0

  • Inside the loop, start another loop for j to 0 and j less than size of an array

  • Check if i = j then continue

  • Else, set temp = temp + arr[j]

  • Now check if temp % arr[i] =0 then increment the value of count by 1

  • Return the count

  • Print the result.

Example

 Live Demo

#include <iostream> using namespace std; int countelements( int arr_1[], int size){    // To store the count of required numbers    int result = 0;    for (int i = 0; i < size; i++){       // Initialize sum to 0       int sum = 0;       for (int j = 0; j < size; j++){          if (i == j){             continue;          }          else{             sum += arr_1[j];          }       }       // If sum is divisible by the chosen element       if (sum % arr_1[i] == 0){          result++;       }    }    // Return the count    return result; } // main function int main(){    int arr_1[] = { 1, 2, 3, 4, 5, 6 };    int size = sizeof(arr_1) / sizeof(arr_1[0]);    cout <<"count is " <<countelements(arr_1, size);    return 0; }

Output

If we run the above code we will get the following output −

count is 2
Updated on: 2020-05-15T12:00:37+05:30

332 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements