Write a program that finds and prints all of the prime numbers between 3 and X (X is input from the user). A prime number is a number such that 1 and itself are the only numbers that evenly divide it (for example, 3, 5, 7, 11, 13, 17, …).
One way to solve this problem is to use a doubly nested loop (a loop inside another loop). The outer loop can iterate from 3 to N while the inner loop checks to see if the counter value for the outer loop is prime. One way to see if number n is prime is to loop from 2 to n-1 and if any of these numbers evenly divides n, then n cannot be prime. If none of the values from 2 to n-1 evenly divides n, then n must be prime.
Note: do not use break statements, and user defined functions.
also tell how many prime numbers are there from 2 to n.
the language to be used is c++
Program:
#include<iostream>
using namespace std;
int main()
{
int X,i,j;
int count=0;
cout<<"Enter value of X: ";
cin>>X;
cout<<"\nPrime Numbers are : ";
for(i=3;i<=X;i++)
{
for(j=2;j<i;j++)
{
if(i%j==0)
{
//use goto instead of the break statement to jump to next
goto jump;
}
}
jump:
if(i==j)
{
cout<<i<<" ";
count++;
}
}
cout<<"\n\nThere are "<<count<<" prime numbers
from 3 to "<<X<<".";
return 0;
}
Output:
Get Answers For Free
Most questions answered within 1 hours.