A prime number is a whole number that is greater than one and the only factors of a prime number should be one and itself. Some of the first prime numbers are 2, 3, 5, 7, 11, 13 ,17 etc.
5, 7, 11, 13, 17 and 19.

Program Code :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
using namespace std;
int main()
{
    int low, high, i, flag;
    cout << "Enter two numbers(intervals): ";
    cin >> low >> high;
    cout << "Prime numbers between " << low << " and " << high << " are: ";
    while (low < high)
    {
        flag = 0;
        for(i = 2; i <= low/2; ++i)
        {
            if(low % i == 0)
            {
                flag = 1;
                break;
            }
        }
        if (flag == 0)
            cout << low << " ";
        ++low;
    }
    return 0;
}

The program to find and display the prime numbers between two intervals is given as follows.

Another Example:

#include <iostream> 
using namespace std; 
void PrimeNumbers (int lbound, int ubound) {   
   int flag, i;
   while (lbound <= ubound) {
      flag = 0;
      for(i = 2; i <= lbound/2; i++) {
         if(lbound % i == 0) {
            flag = 1;
            break;
         }
      }
      if (flag == 0)
         cout<<lbound<<" ";
      lbound++;
   }
}
int main() {
   int lowerbound = 20, upperbound = 50;
   cout<<"Prime numbers between "<<lowerbound<<" and "<<upperbound<<" are: ";
   PrimeNumbers(lowerbound,upperbound);
   return 0;
}


Output:


Prime numbers between 20 and 50 are: 23 29 31 37 41 43 47
In the above program, the function main() contains only the cout object and the function call to the function PrimeNumbers() with upperbound and lowerbound as arguments. This can be seen in the following code snippet.
cout<<"Prime numbers between "<<lowerbound<<" and "<<upperbound<<" are: ";
PrimeNumbers(lowerbound,upperbound);
In the function PrimeNumbers(), each number from lbound to ubound is tested to see if it is prime or not. If it is a prime number, it is displayed. This is done using a while loop.
In the while loop, initial value of flag=0. If the number is not prime, then the value of flag is set to 1 in the for loop. After the end of the for loop, if flag is still 0, then the number is prime and it is displayed. This can be observed from the following code snippet.
while (lbound <= ubound) {
   flag = 0;
   for(i = 2; i <= lbound/2; i++) {
      if(lbound % i == 0) {
         flag = 1;
         break;
      }
   }
   if (flag == 0)
      cout<<lbound<<" ";
   lbound++;
}

Post a Comment

 
Top