#include <iostream>
using namespace std;
void primeNumbers (int a, int b) {
int flag, i;
while (a <= b) {
flag = 0;
for(i = 2; i <= a/2; i++) {
if(a % i == 0) {
flag = 1;
break;
}
}
if (flag == 0)
cout<<a<<endl;
a++;
}
}
int main() {
int a;
int b;
cin >> a;
cin >> b;
primeNumbers(a,b);
}
I'm trying to print primes between a certain interval, but if I set 1 in the interval, it gets printed as well. 1 is not a prime. How do I solve this problm?
Why don't you break the tasks in 2 parts. One function that checks if a number is prime and one function that calls the function in a loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
bool is_prime(int num)
{
// your code
}
void primes_in_range(int first, int last)
{
for (int num = first; num <= last; ++num)
{
// now call is_prime with num and if it returns true print the number
}
}