Display prime numbers

The problem is to get a number and display all numbers up to that number entered, that is prime. I understand that a prime number needs to "only" be divisible by 1 and itself to be prime.
However, i do not know how to write the condition for this loop.I assume it is something along these lines but i cannot get the algorithm correct


1
2
3
4
5
6
7
8
9
for (int i = 0; i < number; i++)
{

if ((number % number == '0' && number % 1 == '0') && !(number % i == '0'))
{

}	

}	
Last edited on
Can you list any example of a number (N), where N%N != 0?
Can you list any example of a number (M), where M%1 != 0?
I bet not. What is always true, does not need to be tested.

You do compare a number to '0'. '0' is not a number. It is a character. It has some numeric value, but that value is not 0. is 0.

You start your loop from 0. Therefore, you do divide by 0. That is not healthy. You should focus on the interesting numbers and they are between 1 and the number.


A number N is a prime, if no smaller number M (where 1<M) can divide it.
We start by presuming that N is prime. We store that assumption in a boolean variable.
Then we look at the possible divisors, one by one. If the currently studied M can divide N, then our assumption is wrong, so we set the variable false.

We did start with variable set to true. Nothing in the loop sets it true. Something in the loop can turn it false. After the loop the variable holds the answer.
So what would the loop look like ?
Topic archived. No new replies allowed.