Write a program that finds and prints all of the prime numbers between 3 and n.
ID: 3630276 • Letter: W
Question
Write a program that finds and prints all of the prime numbers between 3 and n. The program should allow the user to input n. 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. 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 m is prime is to loop from 2 to m – 1 and if any of these numbers evenly divides m, then m cannot be prime. (Note that there are several ways to make this algorithm more efficient.)
//Header files
#include<iostream>
using namespace std; int main()
{
Explanation / Answer
#include <iostream>
using namespace std;
int main ()
{
int prime;
int n;
cout << "Enter a number bigger than 3" << endl;
cin >> n; //
if(n < 3)
cout << "INVALID ENTRY" << endl;
else
{
for(prime=3; prime <= n; prime= prime+2)//even# are never prime
{
for(int count=2; count < prime; count++)//checking if #is prime
{
if(prime % count > 0 and count == prime-1 ) //if remainder zero
cout << prime << " is a prime number" << endl;
else if(prime % count == 0)//if remainder=zero endloop
count = prime;
}
}
}
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.