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.

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.

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.

This content requires that you purchase additional access. The price is $2.99 or free for our Make Life Easier and 30 Days – Not Recurring members.

Purchase this Content ($2.99) Choose a Membership Level