#include <iostream>
using namespace std;
int main()
{
int low, high, i, j, is_prime;
cout << "Enter two positive integers: ";
cin >> low >> high;
cout << "Prime numbers between " << low << " and " << high << " are: " << endl;
// Loop through each number between low and high
for (i = low; i <= high; i++) {
// Assume the number is prime
is_prime = 1;
// Check if the number is divisible by any number from 2 to i/2
for (j = 2; j <= i/2; j++) {
if (i % j == 0) {
// If the number is divisible, it is not prime
is_prime = 0;
break;
}
}
// If the number is prime, print it to the console
if (is_prime) {
cout << i << endl;
}
}
return 0;
}
Enter two positive integers: 2
30
Prime numbers between 2 and 30 are:
2
3
5
7
11
13
17
19
23
29
cout
. We then read the integer inputs using cin
.is_prime
variable to 1. We then check if the number is divisible by any number from 2 to half of the number using another loop. If the number is divisible by any of these numbers, we set the is_prime
variable to 0 and break out of the loop.is_prime
variable is still 1. If it is, we print the number to the console using cout
.#include <iostream>
using namespace std;
int main() {
int low, high, temp, i;
bool is_prime;
cout << "Enter two numbers (intevals): ";
cin >> low >> high;
//swapping numbers if low is greater than high
if (low > high) {
temp = low;
low = high;
high = temp;
}
cout << "\nPrime numbers between " << low << " and " << high << " are:" << endl;
while (low < high) {
is_prime = true;
if (low == 0 || low == 1) {
is_prime = false;
}
for (i = 2; i <= low / 2; ++i) {
if (low % i == 0) {
is_prime = false;
break;
}
}
if (is_prime)
cout << low << ", ";
++low;
}
return 0;
}
Enter two numbers (intevals): 30
2
Prime numbers between 2 and 30 are:
2, 3, 5, 7, 11, 13, 17, 19, 23, 29,