Wrong output looking for prime numbers

Jun 18, 2010 at 1:10pm
I'm trying to write some code that outputs the prime numbers from 3 up to 100. Here's what I've wrote so far, but I have no idea why the output is EVERY number from 3 to 100. I tried changing the AND (&&) to OR (||), but got the exact same results. Thanks:

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
#include <iostream>

using namespace std;

int main()
{
	bool isPrime = true;

	for(int i = 3; i <= 100; i++)
	{
		for(int j = 2; j <= 100; j++)
		{
			if(i != j && i % j == 0)
			{
				isPrime = false;
				break;
			}
		}

		if(isPrime = true) cout << i << " ";

		isPrime = true;
	}

	return 0;
}
Jun 18, 2010 at 1:15pm
Classic mistake:

if(isPrime = true)
Jun 18, 2010 at 2:05pm
I can't test this just now, but I'm guessing I should have:

if(isPrime == true)

or

if(isPrime)

??
Jun 18, 2010 at 2:06pm
Either one would have worked.

-Albatross
Jun 18, 2010 at 2:18pm
also,

you only need divisors up to the square root of the maximum
on the inner loop.

with any other product: A x B

one of A or B must have a value less than the square root.
or both equal to the root.


Last edited on Jun 18, 2010 at 2:19pm
Jun 18, 2010 at 3:10pm
Just an oppinion but i think adding '\n' where " " would make it look better. Instead of alligning them all on the same line and the "Press any key to continue"
being on the same line, it would make each number be on its own line.
Topic archived. No new replies allowed.