Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,894 questions

51,825 answers

573 users

How to check if at least one number of a vector are divisible by N in C++

2 Answers

0 votes
#include <algorithm>
#include <iostream>
#include <vector>
 
int main() {
    std::vector<int> vec = { 5, 2, 7, 1, 9, 3, 6, 4 };
    
    struct DivisibleByN {
        const int N;
        DivisibleByN(int element) : N(element) {}
        bool operator() (int element) const { return element % N == 0; }
    };
    
    int N = 7;
    
    if (std::any_of(vec.cbegin(), vec.cend(), DivisibleByN(N))) {
        std::cout << "At least one number is divisible by " << N;
    }
}
    
    
      
     
/*
run:
     
5 2 7 1 9 3 6 4 
     
*/

 



answered Aug 1, 2023 by avibootz
0 votes
#include <iostream>
#include <algorithm>

using namespace std::placeholders;
 
bool DivisibleByN(int N , int d) {
    return N % d == 0;
}
 
int main() {
    std::vector<int> vec = { 5, 2, 7, 1, 9, 21, 3, 6, 14 };
    int N = 7;
     
    int count = std::count_if(vec.cbegin(), vec.cend(), std::bind(&DivisibleByN, _1, N));
    
    if (std::any_of(vec.cbegin(), vec.cend(), std::bind(&DivisibleByN, _1, N))) {
        std::cout << "At least one number is divisible by " << N;
    }
}
 
 
 
/*
run:
 
At least one number is divisible by 7
 
*/

 



answered Aug 1, 2023 by avibootz
...