Your exit condition in for(j=2;
j <= (i/j); j++) is recomputed after each iteration. When i==11, and j==4, j <= (i/j) => 4 <= 11/4 => 4 <= 2.75 which is false, so your for loop terminates.
Your inner for loop will never process j=5, 6, 7, 8... It will stop at 4, and in fact will only process j=1,2,3 when i==11.
The code you have:
1 2 3
|
if(j > (i/j))
cout << i << " is prime\n";
}
|
can never be reached because j > (i/j) can never be true inside your for loop. The exit condition being j <= (i/j) forbids it.
j > (i/j) and j <= (i/j) cannot be true at the same time.
j is incremented after each iteration through the for loop, and as such, the value of i/j is also changing. I suspect you want your for loop to exit on a set value. Try doing something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
int i, j;
for(i=2; i<100; i++)
{
int half = i/2;
int found = 1;
for(j=2; j <= half; j++)
{
if(!(i%j)) {
found = 0;
break; // if factor found, not prime
}
}
if(found)
cout << i << " is prime\n";
}
|
For a better understanding of what's going on in your code, print out each value of i and j with this and look at the output:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
#include <iostream>
using namespace std;
int main() {
int i, j;
for(i=2; i<10; i++) {
cout << "i = " << i << endl;
for(j=2; j<10; j++) {
cout << "j = " << j << endl;
}
}
}
|
EDIT: had the found var backwards. should be initialized to 1 and set to 0 in your check.