Write a c++ program to display the prime numbers in the range n1 and n2
Answers
Answered by
0
Intervals
#include <iostream>
using namespace std;
int checkPrimeNumber(int); int main() { int n1, n2; bool flag; cout << "Enter two positive integers: "; cin >> n1 >> n2; cout << "Prime numbers between " << n1 << " and " << n2 << " are: "; for(int i = n1+1; i < n2; ++i) { // If i is a prime number, flag will be equal to 1 flag = checkPrimeNumber(i); if(flag) cout << i << " "; } return 0; } // user-defined function to check prime number int checkPrimeNumber(int n) { bool flag = true; for(int j = 2; j <= n/2; ++j) { if (n%j == 0) { flag = false; break; } } return flag; }
#include <iostream>
using namespace std;
int checkPrimeNumber(int); int main() { int n1, n2; bool flag; cout << "Enter two positive integers: "; cin >> n1 >> n2; cout << "Prime numbers between " << n1 << " and " << n2 << " are: "; for(int i = n1+1; i < n2; ++i) { // If i is a prime number, flag will be equal to 1 flag = checkPrimeNumber(i); if(flag) cout << i << " "; } return 0; } // user-defined function to check prime number int checkPrimeNumber(int n) { bool flag = true; for(int j = 2; j <= n/2; ++j) { if (n%j == 0) { flag = false; break; } } return flag; }
Answered by
0
int a,b,c,n1,n2;
ask the user to enter the value of n1 and n2;
for(int i=n1;i<=n2;i++)
{ for(int j=2;j<n1;j++)
{ if (i%j==0)
break;
else
cout<<i<<endl;
}
}
ask the user to enter the value of n1 and n2;
for(int i=n1;i<=n2;i++)
{ for(int j=2;j<n1;j++)
{ if (i%j==0)
break;
else
cout<<i<<endl;
}
}
Similar questions
In each iteration, whether low is a prime number or not is checked and the value of low is incremented by 1 until low is equal to high.
Visit this page to learn more on how to check whether a number is prime or not.
If the user enters larger number first, this program doesn't work as intended. You can solve this issue by swapping the numbers if the user enters larger number first.