### LANGUAGE: C++

### CHALLENGE:

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.)

SAMPLE RUN #1: ./ETest

Instructor Notes:

The prompt to give for the user input should be exactly “Enter n (to print primes from 3 to n): ”

And output each prime number x exactly as “x is a prime number.”, followed by a line break.

### SOLUTION:

#include &lt;iostream&gt; using namespace std; int main(){ bool isPrime=true; int n ; cout &lt;&lt; enter the number ; cin &gt;&gt; n ; for(int primeCandidate=3; primeCandidate&lt;=n; primeCandidate++){ isPrime = true; for(int factor=2; factor&lt;primeCandidate-1; factor++){ if(primeCandidate%factor == 0){ isPrime = false; break; } } if(isPrime == true){ cout&lt;&lt; primeCandidate &lt;&lt; " is prime." &lt;&lt; endl; } } return 0; }