having trouble with prime algorithm finding prime numbers inside arrays

this is my program.... it gets array input from user... then goes threw the data and finds prime numbers.... I've changed around the code plenty of times and still doesn't work correctly.

I think the problem is in the while loop, but, maybe it's elsewhere.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <math.h>
#define crack 11
using namespace std;

int main() 
{

int num[crack];

int a, b, c, d;
bool e = 1;
for (a = 0; a <= crack - 1; a++) 
{
cout << "Enter number:";
cin >> num[a];
}

b = 2;
for ( c = 0; c < crack; c++){
e = 1;
while ( b <= sqrt(static_cast<double>(num[c])))
{
if ( num[c] % b == 0) 
{
e = 0;
break;
}
b++;
}

if (e = 1)
cout << num[c] << " is prime." << endl;
else 
cout << num[c] << " is not  prime." << endl;
}
return 0;
}
Last edited on
Hi,

Line 32 should be if(e==1) if you want to do a comparison... or else it's assigning e=1 (which returns 1) regardless of what e is.

Your variable b needs to be reset for each new number you're testing... try shifting b=2 from line 19 to somewhere in the loop.
i fixed my problem by using two functions.... one for setting the array and its data and the other
to find if it was prime... i also made it so you can pick the length of an array... enjoy

and if anyone posted i didn't see yet but thanks for your input...

updated program that works:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
#include <math.h>
using namespace std;

void find_prime(int b);

int main()
{
int a;

cout << "How many numbers do you want to find prime numbers for:";
cin >> a;

int array[a];

int c;
for (c = 0; c < a; c++)
{
cout << "Enter a number:";
cin >> array[c];
}


for (c = 0; c < a; c++)
{
find_prime(array[c]);
}

cout << endl << "Program was created by brokenbot\n";
return 0;
}

void find_prime(int b)
{
int a = b;
int c = 2;
bool g = true;
while (c <= sqrt(static_cast<double>(b)))
{


if (b % c == 0)
{
g = false;
break;
}
c++;
}

if (g)
{
cout << a << " is prime\n";}
else 
{cout << a << " is not prime\n";}

}
oh wow... now i see 2 little flaws i made... lmao thanks a lot man.... that would of kept me going for a day... lol
for got assignment and test for equality difference already...
Last edited on
Topic archived. No new replies allowed.