Skip to content
Related Articles

Related Articles

Improve Article

Find elements of an array which are divisible by N using STL in C++

  • Last Updated : 18 Dec, 2019

Given an array and an integer N, find elements which are divisible by N, using STL in C++

Examples:

Input: a[] = {1, 2, 3, 4, 5, 10}, N = 2
Output: 3
Explanation:
As 2, 4, and 10 are divisible by 2
Therefore the output is 3

Input:a[] = {4, 3, 5, 9, 11}, N = 5
Output: 1
Explanation:
As only 5 is divisible by 5
Therefore the output is 3

Approach: This can be achieved using count_if() method in C++

Syntax:

count_if(lower_bound, upper_bound, function)

where function takes the element of given sequence one by one as a parameter and returns a boolean value on the basis of condition specified in that function.



In this case, the function will be:

bool isDiv(int i)
{
    if (i % N == 0)
        return true;
    else
        return false;
}

Below is the implementation of the above approach:




// C++ simple program to
// find elements which are
// divisible by N
  
#include <bits/stdc++.h>
using namespace std;
  
int N;
  
// Function to check
// if the element is divisible by N
bool isDiv(int i)
{
    if (i % N == 0)
        return true;
    else
        return false;
}
  
// Driver code
int main()
{
    int a[] = { 1, 2, 6, 3, 4, 5 };
    N = 2;
  
    int n = sizeof(a) / sizeof(a[0]);
  
    int count = count_if(a, a + n, isDiv);
  
    cout << "Elements divisible by "
         << N << ": " << count;
  
    return 0;
}
Output:
Elements divisible by 2: 3
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for the language and STL. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
My Personal Notes arrow_drop_up
Recommended Articles
Page :