Write a program that assigns Twenty random numbers to an array and counts all prime numbers entered by the user. The program finally displays a total number of primes in the array.
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
bool IsPrime(int x){
if(x == 2) return true;//2 is prime
if(x%2==0) return false;//check even
for(int i=3;i*i<=x;i+=2) //check odd
if(x%i==0) return false;
return true;
}
int main(){
srand(time(NULL)); //seed for random
int array[20];
int primeCounter = 0;
for(int i = 0; i < 20; i++)
{
array[i] = rand()%10;//rand()%10 means random value from 0 to 10,
//you can change this value or delete it
if(IsPrime(array[i]))
primeCounter++;
}
cout << primeCounter;
}
Comments
Leave a comment