Question about a Program to print out prime numbers up to a given number

Hello,

I am trying to write a program that will print out all prime numbers in a range of numbers (say from 0 to whatever).

I am not sure why my code is producing wrong output.

Here is what I wrote so far.

Thank you,

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
27
28
29
30
#include <iostream>

using namespace std;

int main()
{
    int i, number, range;
    number = 1;
    i = 1;
    int counter;
    counter = 0;
    cout << "Enter a number to set the range:" << endl;
    cin >> range;
    while (number <= range) {
        while(i <= number) {
            if (number % i == 0) {
                counter++;
            }
            i++;
            if (counter == 2) {
            cout << number << " is a prime number." << endl;
            counter = 0;
            }
        }
        i = 1;

    number++;
    }
    return 0;
}
This is my fastest solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
bool IsPrime(unsigned int n)
{
	// 0 or 1 is not prime
	if(n == 0 || n == 1) return 0;
	// 2 and 3 are
	if(n == 2 || n == 3) return 1;
	// if number is even, definitely not prime
	if(n % 2 == 0) return 0;
	// if number is greater than 3 and not even
	// test numbers against it
	for(unsigned int i = 3; i < n/2+1; i+=2)
	{
		//if n / i = 0, not prime
		if(n%i == 0) return 0;
	}

	// if execution gets here, it is a prime number
	return 1;
}
Topic archived. No new replies allowed.