Project 14: Prime Numbers. Write a program that reads in an integer that is grea
ID: 3543936 • Letter: P
Question
Project 14: Prime Numbers. Write a program that reads in an integer that is greater than 2 (let's call it k) and finds and prints all of the prime numbers between 3 and k. 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 k 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 that there are several easy ways to make this algorithm more efficient.)
Input Details: The input consists of just one integer which you may assume is 3 or greater. There is no prompt.
Output Details: Each prime number is printed at the beginning of a new line and is followed by the predicate "is a prime number."
Explanation / Answer
#include <iostream>
using namespace std;
int main()
{
bool isPrime=true;
int n ;
cout << enter the number ;
cin >> n ;
for(int primeCandidate=3; primeCandidate<=n; primeCandidate++)
{
//Reset isPrime to true
isPrime = true;
//Check the factors
for(int factor=2; factor<primeCandidate-1; factor++)
{
//If a factor is found, the number is not prime. No reason to check
//the rest of the numbers, so break out of this 'for' loop.
if(primeCandidate%factor == 0)
{
isPrime = false;
break;
}
}
//If the number is prime, print it.
if(isPrime == true)
{
cout<< primeCandidate << " is prime." << endl;
}
}
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.