i'm in a beginning c++ class and we have to write a program that finds all primes between 2 and 100 within a doubly nested loop. i feel like i'm really close but i think i've been doing it too long and can't figure out what i'm doing wrong......

``````int main ()
{

int i = 0;
int j = 0;
bool isPrime;

for (i = 2; i < 99; i++)
{
isPrime = true;

for (j = 2; j < i; j++)
{
if (i%j == 0)
{
isPrime = false;
break;

}
else
if (isPrime == true)
cout << i << endl;

}

}

return 0;
}``````

scratch that..... i think i got it

deleted the else on line 20, but more importantly, moved the:

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

to the right loop. DOH!

scratch that..... i think i got it

deleted the else on line 20, but more importantly, moved the:

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

to the right loop. DOH!

Would also say that you can skip out of 2 early, and then count only odd numbers from 3 up inside j. (You check if it's divisible by 2 as a special case, then start at three and +=2 each time-- if it divided by 2 you don't need to check 4,6,8, etc)

wow. you would totally have to show me how to write that. that little bitty program i wrote took me all weekend, and ate up most of today.

i'm really having a hard time with c++.

and most of the time, i stumble upon the solution just by tinkering with the code. i dont always understand the code that i've written. that's bad huh? haha

Here's a code snippet I wrote a while back that you might find useful. It isn't the only way to do it, but it has a nested loop and takes advantage of some efficiencies such as not testing 4, 6, 8, ... as the previous poster mentions. Nor will it test 9, 15, 21, etc, which are all multiples of 3. It doesn't really "test" a number for primeness, hence it doesn't use the % operator. Instead, it multiplies prime numbers in order to flag the products as non-prime. Anything not flagged at the end is prime.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.