Write a C++ Program to Display Prime Numbers Between Two Intervals

C++ Program to Display Factors of a Number

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn C++ programming concepts. You can learn C++ language at your own speed and time. One can learn concepts of C++ language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

C++ Program to Display Factors of a Number
C++ Program to Display Factors of a Number

Write a C++ Program to Display Prime Numbers Between Two Intervals

1.PROGRAM:C++ Program to Display Prime Numbers Between Two Intervals

/* C++ Program to Display Prime Numbers Between Two Intervals*/

#include <iostream>
using namespace std;

int main() {

int low, high, i;
bool is_prime = true;

cout << “Enter two numbers (intervals): “;
cin >> low >> high;

cout << “\nPrime numbers between ” << low << ” and ” << high << ” are: ” << endl;

while (low < high) {
is_prime = true;

// 0 and 1 are not prime numbers
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;
}

2.PROGRAM:Display Prime Numbers When Larger Number is Entered first

/* Display Prime Numbers When Larger Number is Entered first */

#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;
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *