Hey. Im trying to make program that basically displays all the prime

numbers. I need to use bool and for but im not quite sure if i have this

right. So far i have this bunch of a mess but can anyone point me in the

right direction? Thanks!

First ask yourself what is a primenumber?

"An integer p is called a prime number if the only positive integers

that divide p are 1 and p itself."

So you need to check your would-be primenumber against all other

integers. Well you do not need to check againts all other integers.

Any integer larger than p will not divide p!

So we need to check all integers smaller than p (excluding 0 and 1).

This is something you should definitely use a loop for.

You can use a "while()" loop, but i would prefer a "for()" loop.

something like for(int n= 2; n<p;n++) in side the loop you can then

check if n divides p. If it does, p is not a prime.

If the loop completes without n dividing p, p is a prime.

If you put all this into a function called IsPrime(int p) which can

return a bool. ( true if the argument was a primenumber, false if

not)

if you now want test a number you can call

if(IsPrime(number_to_test))

{

// This was a prime number

}

You can now use a loop to test all the numbers you would like...

(hint "for loop") or you can write each test explicitly

if(Isprime(2))

:

:

if(Isprime(34))

I know there is a lot of room for improvement in my is prime

function. But start by focussing on getting the function to work

correctly first, then you can always optimise the code if needed.

One optimization is only to test integers smaller than or equal to

the squareroot of p. another ( and more difficult) is to only test a

against all primenumbers smaller than the square root of p, provided

you know ALL of them!!

Two things I think you should consider is what should happen is you

call IsPrime(0) and IsPrime(1). You wil probably have to modify the

IsPrime function to handle this in a sensible way.

A few comments on the code:

using namespace std;

See

http://www.parashift.com/c++-faq-lit...standards.html
section 27.5 for a discussion.

You need to use more comments in your code!

If you have a varible, you should make a comment why its there, and

what is is used for. The same applies to functions and files.

make it a good habbit to write many comments, and most importantly

keep the comments in sync with the code!

cout << sqrt(static_cast<double>(100)) << endl;

Using a cast operator is something that should make you think "Is

this really right?". Casting is often a consecuence of a flawed

design. In some cases there are needed, but avoid them as much as

possible.

I hope this get you closer to your program.

Bo Møller

--

Bo Møller

Hobby-Programmer