Help

OK I need to make a program that determines how many numbers are prime from an array of 5 ints.

My program ( that doesn't work ) :

#include <iostream>
using namespace std;
int main() {
int n, a[5],i,p,d;
cin>>n;
for (i=0;i<n;i++)
cin>> a[i];
for (d = 3; d<=a[i]; d++)
{
if (a[i]%d==0) p=p;
else p=p+1;
};
cout<<p<<' ';
return 0;}

The main thing that I see is that p is not initialized. Initialize it to 0.

Also, your test for prime is a bit funky. You just check if the number is divisible by the numbers stored in a[2], a[3] or a[4] (assuming that n is 5). You should implement a function that will check if a[i] is divisible by any number from 2 to the square root of the number.

Topic archived. No new replies allowed.