Answer to Question #186894 in C++ for aditya

Question #186894

Write a program to count the number of prime number elements in an array of 10 elements where array is allocated memory dynamically


1
Expert's answer
2021-04-28T16:46:07-0400
#include <iostream>
#include <random>

bool IsPrime(int v) {
    if (v < 2) return false;
    int divs = 0;
    for (int i = 2; i * i < v + 1 && !divs; i++) {
        if (v % i == 0) divs++;
    }
    return !divs;
}

int main() {
    std::random_device r;
    std::mt19937 engine(r());
    const int size = 20;
    const int maxValue = 64;
    int *a = new int[size];
    for (int i = 0; i < size; i++) {
        a[i] = engine() % maxValue;
    }
    std::cout << "Array:  ";
    for (int i = 0; i < size; i++) {
        std::cout << a[i] << " ";
    }
    std::cout << "\nPrimes: ";
    for (int i = 0; i < size; i++) {
        if (IsPrime(a[i])) {
            std::cout << a[i] << " ";
        }
    }
    delete[] a;
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS