Prime numbers outputting '1'

I'm trying to output prime numbers in an user inputted range, but with testing, when I input 1 and 10, it'll show all the prime numbers, but it will also input 1. I've tried rearranging and deleting/adding code, but it only seems to make it worse. This is my for/if loop that works with the '1' being outputted.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
bool prime = true;
		for (int testNum = first; testNum <= second; testNum++)
		{
			for (int div = 2; div < testNum; ++div)
			{
				if (testNum % div == 0)
				{
					prime = false;
					break;
				}
				else if (testNum == 1)
				{
					prime = false;
					break;
				}

				else if (testNum % div != 0)
				{
					prime = true;
				}
			}
		if (prime)
			cout << testNum << " ";
		}
Is your problem that it's outputting the number 1? Because you do realize the number 1 is a prime number, right?
Well, a prime number by definition is a number that is divisible by 2 divisors, that number and 1. I realize that, but in the book I have, it shows in a range of 1-10, the numbers should output 2, 3, 5, and 7.
1 is neither prime nor composite. Just make sure to start checking for primes after 1.
Doesn't my code do that? If not, how?
First of all, thank you @LB for pointing that out, I had forgotten.

Your problem is in the second for-loop.

Since it's int div = 2; div < testNum; And testNum starts at 1, it will skip that for-loop and directly go to the if (prime) and print out the number 1.

If you don't want it to print out the number 1, you need to start your bool as false, rather than true. So just change

bool prime = true; to bool prime = false; and it should run perfectly fine.

Edit: I found out the problem in 30 seconds by debugging the program. Debugging is very important and you should definitely learn how to do it.
Last edited on
Okay, so I did that. But now it doesn't output the 2. Which it should. I tried making it so that
 
for (int div = 2; div <= testNum; ++div)

But that just made it so that nothing output.
Okay, so I did that, but it also stopped outputting the 2. I tried changing the for loop to:
 
for (int div = 2; div <= testNum; ++div)

But that didn't work either because nothing output when <= is added instead of <
Honestly I would just take LB's advice. I don't see any reason as to why you would want to start at 1, other than your book saying it, which you don't have to listen to really. Just use your original code and do the logical thing of starting at 2, saves you a lot of time and headache.
closed account (48T7M4Gy)
https://primes.utm.edu/notes/faq/one.html
Topic archived. No new replies allowed.