Detecting prime numbers

My solution seems quite different from the one in the 'Solution Guide'.
Will mine detect all primes or will it break? It appears to work but
I don't know enough to be sure. Thanks for any insight.

b52

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;

int main()
{
  int i,j;
  for (i = 2; i < 1000; i++)
  {
    for (j = 2; j < i; j++)
      if (i % j * j == 0) break;
    if (j < i)
      continue;
    else
      cout << i << endl;
  }
  return 0;
}
What's the point of the "* J" on line 10? i%j*j can only ==0 if j==0 or i%j==0, and j can never be zero.
I see what you mean. When I googled prime formula I must have misunderstood the information that I read. Thanks, I would never have noticed that - even when I debugged the code.

b52
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
I variant :

#include <iostream>
using namespace std;

int main()
{
    int  count=0;
    for(int i=2; i<1000; i++) 
    {
        for(int j=2; j<i; j++) 
        {
            if(i%j==0)
                count++;
        }
        if(count==0)
        {
            cout<<"Prime: "<<i<<endl;
            count =0;
        }
        else
            count =0;    
    }  
    
    return 0;
}

II variant :

#include <iostream>
using namespace std;

int main()
{
    for(int i =2; i<1000; i++)
    {
        if((i%2!=0 && i%3!=0 && i%5!=0)|| ( i==2 || i==5 || i==3))
            cout<<"Prime : "<<i<<endl;
    }
    return 0;
}
The second variant doesn't work. The first one is inefficient.
Yea, first is inefficient, but why you're saying that second variant doesn't work? Do you had tried it?
No but its obvious it doesnt work because it only tries divisions by 2, 3, and 5, not all other prime numbers that come after those

(It would say, 21 is a prime number, even though 21%7 == 0)
Last edited on
helios is right the second one won't work. 169 is not divisible by 2,3 or 5 but is not a prime number
PROTIP: It's not necessary to test something to demonstrate that it's incorrect, and just because something passes a test, it doesn't make it correct. Testing can only prove the presence of bugs, not their absence.
closed account (D80DSL3A)
Agreed that 2nd method won't work. Skillless needed a higher # for his counter example as 21%3==0 is tested for. Method fails if lowest prime factor is > 5 so lowest "false positive" comes for 7*7 = 49.
Oh lol yeah ofcourse, sorry >.> my brain doesnt work when im in an office
Topic archived. No new replies allowed.