Find a number that divides maximum array elements in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to find the number that is divided into maximum elements in the given array.

Let's see the steps to solve the problem.

  • Initialize the array and a variable to store the result.

  • Iterate over the array.

    • Initialize the counter variable.

    • Iterate over the array again.

      • Increment the counter if the current element is divisible by the array element.

    • Update the result if the current count is maximum.

  • Print the result.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int numberWithMaximumMultiples(int arr[], int n) {
   int result = -1;
   for (int i = 0; i < n; i++) {
      int count = 0;
      for (int j = 0; j < n; j++) {
         if (arr[i] % arr[j] == 0) {
            count++;
         }
      }
      if (count > result) {
         result = count;
      }
   }
   return result;
}
int main() {
   int arr[] = {4, 24, 16, 3, 12, 28};
   cout << numberWithMaximumMultiples(arr, 6) << endl;
   return 0;
}

Output

If you execute the above code, then you will get the following result.

4

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Published on 01-Feb-2021 11:50:21
Advertisements