Project 14: Prime Numbers. Write a program that reads in an integer that is grea
ID: 639465 • 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;
bool prime(int i){
int k = 2;
while (k*k <= i){
if (i % k == 0)
return false;
k += 1;
}
return true;
}
int main() {
int n;
cout << "Enter the number n : ";
cin >> n;
for (int i = 3; i <= n; i+= 2){
if (prime(i))
cout << i << " is a prime number " << endl;
}
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.