Prime numbers in a range

I'm trying to write this program to test and output all prime numbers in a range given by the user. I posted this code before, but I have a different problem now. Right now, it mostly works except that when the outputs are in the single digits, then it won't output as I want, but anything past that, it will output everything correctly as far I can tell. I also had the inside if written as if (start % div == 0 || start % 3 == 0), which also let single digits primes (except 2) print out, but then higher number non-primes, starting at 49 I think, started to output. I was also thinking about using a bool flag which I added in a variable for, but don't quite know how to use.

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
31
32
33
34
35
36
#include <iostream>
#include <conio.h>
#include <math.h>

using namespace std;

int main()
{
int first, second;                                      
bool notPrime = true;                                   

cout << "Please enter the first number: ";              
cin >> first;
cout << "Please enter the second number: ";             
cin >> second;
cout << "The prime numbers between " << first << " and " << second << " are: ";

if (first < second)                                 
{
    for (int start = first; start <= second; start++)
    {
        for (int div = 2; div < start; div++)
        {
            if (start % div == 0 || start % 3 == 0 || start % 5 == 0 || start % 7 == 0)
                break;
            else if (start % div != 0)
                {
                cout << start << " ";
                break;
                }
        }
    }
}
_getch();
return 0;
}
> but anything past that, it will output everything correctly as far I can tell
no, if the condition in line 24 fails then the one ine line 26 would succeed, always.

what's more, either path woud terminate the loop.
`div' would no go farther than 4, you only test against 2, 3, 4, 5, and 7.


Review the conditions for a number to be prime.
Also, to simplify the code, create a function bool is_prime(int number) then you may do
1
2
3
for(int number = start; number <= finish; ++number)
   if( is_prime(number) )
      std::cout << number << ' ';
Topic archived. No new replies allowed.