Reputation: 508
I am new to computer science and had a quick question. I was trying to make a program that would take two integer inputs and print out all of the prime numbers in between them.
The problem I am having is that when I use break in the nested for loop. After it finds a prime number, it does not hit the nested for loop on the next go around of the outside for loop. Therefore, when searching for prime numbers between say 8 and 15, it will print out "11 12 13 14 15." It is correct at first but after finding a prime, it states that the rest of the bounded numbers are also primes.
#include <iostream>
using namespace std;
int main()
{
// Prime number finder:
cout << "Enter two numbers and I will find the prime numbers between them.\n\n";
int num1, num2, i = 2;
bool valid;
cout << "Enter the lower limit: ";
cin >> num1;
cout << endl << "Enter the higher limit: ";
cin >> num2;
if (num2 <= num1)
{
cout << "Enter a number that is larger than the lower limit./n";
}
if (num1 <= 1)
{
cout << "1 2 ";
num1 = 3;
}
else if (num1 == 2)
{
cout << "2 ";
num1 = 3;
}
for (num1; num1 <= num2; num1++)
{
valid = true;
for (i; i < num1; i++)
{
if ((num1 % i) == 0)
{
valid = false;
break;
}
}
if (valid == true)
cout << num1 << " ";
}
return 0;
}
Upvotes: 0
Views: 435
Reputation: 22624
The problem is that you don't reset the value of i. Change your loop to:
for (int i = 2; i < num1; i++)
And delete your earlier definition of i
, since it's not needed at that point.
Even better, change the whole check of whether the number is prime to a separate funcion which returns a bool.
This should teach you to write functions with a single responsibility. Your function loops through a bunch of numbers, and for each of them it checks whether it is a prime. This latter part belongs to a separate function. What is interesting is that your bug is highly unlikely to appear if you write the separate functions in the first place.
Upvotes: 3
Reputation: 7610
In the for loop below i is uninitialized, you have to set i=2
, also set the upper bound as sqrt(num1)
.
for (i=2; i <= sqrt(num1); i++)
{
if ((num1 % i) == 0)
{
valid = false;
break;
}
}
To use sqrt()
also include the following header file as follows,
#include<cmath.h>
Upvotes: 1