Detecting prime numbers

Jul 29, 2010 at 2:32am
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;
}
Jul 29, 2010 at 2:42am
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.
Jul 29, 2010 at 4:26am
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
Jul 29, 2010 at 10:44am
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;
}
Jul 29, 2010 at 2:25pm
The second variant doesn't work. The first one is inefficient.
Jul 29, 2010 at 2:45pm
Yea, first is inefficient, but why you're saying that second variant doesn't work? Do you had tried it?
Jul 29, 2010 at 2:54pm
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 Jul 29, 2010 at 2:55pm
Jul 29, 2010 at 2:57pm
helios is right the second one won't work. 169 is not divisible by 2,3 or 5 but is not a prime number
Jul 29, 2010 at 3:40pm
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.
Jul 29, 2010 at 6:53pm
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.
Jul 29, 2010 at 6:56pm
Oh lol yeah ofcourse, sorry >.> my brain doesnt work when im in an office
Topic archived. No new replies allowed.