[Solved] How to Systematically use each item in a Vector [closed]


First, you will need to push your prime numbers in the vector. At the beginning, unless you ask otherwise, the vector is empty. You can push a prime number using this snippet:

// somewhere you declare your vector
std::vector<unsigned long long> primes;

// code computing a prime number
unsigned long long prime;
.... 

// Push the new prime number at the end of the vector
primes.push_back(prime);

Then you will need to loop through all the prime numbers in the vector. You can use a for loop:

for(auto prime : primes) {
    . . . // code using the prime number
}

As suggested by comments, you may want to use this for loop in order to test the primality of a number. You can easily do it with the for loop:

unsigned long long number = ...; // the number to test
bool is_prime = true;
for(auto prime: primes) {
    bool is_divisible = (0 == number % prime)
    is_prime = is_prime && !is_divisible;
    if(! is_prime)
        break;
}
// then push it in primes if it is prime
if(is_prime)
    primes.push_back(number);

Please follow the link provided by @tobi303 which is a very good resource on C++.

C++ is not easy for beginners, but if you hang on it is rewarding.

4

solved How to Systematically use each item in a Vector [closed]