A prime number is a natural number greater than 1 that has no positive divisors
ID: 3812386 • Letter: A
Question
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. A natural number greater than 1 that is not a prime number is called a composite number.
Create a C++ program that utilizes nested for loop that asks the user for a number then the program should compile a list of all natural numbers from 2 to the number the user keyed in marking with a star the prime numbers only.
1. Asks the user for number.
2. List all numbers from 2 to the user typed number.
3. Mark the Prime number with a stars leaving the composite numbers not labeled.
4. Stars should increment keeping track of the prime numbers found previously.
5. In case no Prime numbers is found your program should notify the user.
6. Make sure to check your program for values over 180.
Example Run:
PLEASE ENTER A NUMBER: 1
** NO PRIME NUMBERS WERE FOUND
DO YOU WANT TO TRY AGAIN (Y/N)? y
PLEASE ENTER A NUMBER: -23
** Negative integers can’t be prime, try using positive values
DO YOU WANT TO TRY AGAIN (Y/N)? y
PLEASE ENTER A NUMBER: 15.6
** No floating point is allowed try whole numbers only
DO YOU WANT TO TRY AGAIN (Y/N)? y
PLEASE ENTER A NUMBER: 28
2 *
3 **
4
5 ***
6
7 ****
8
9
10
11 *****
12
13
14
15
16
17 ******
18
19 *******
20
21
22
23 ********
24
25
26
27
28
FOUND 8 PRIME NUMBERS
DO YOU WANT TO TRY AGAIN (Y/N)? n
Thank you goodbye ...
Explanation / Answer
#include<iostream>
using namespace std;
int checkPrime(int val);
int main(){
int num = 0, i = 0 , j = 0 ,count = 1, ret = 0;
float input = 0.0f;
char ch = 'y';
for(; (ch == 'y') || (ch == 'Y');){
cout<< "PLEASE ENTER A NUMBER : ";
cin>> input;
num = (int)input;
if( num < 0){
cout <<"** Negative integers can’t be prime, try using positive values" <<endl;
}
else if( (input - num) != 0) // Floating point value as input will result in non-zero value
{
cout <<"** No floating point is allowed try whole numbers only" <<endl;
}
else if((num == 0) || (num == 1)){
cout<<"** NO PRIME NUMBERS WERE FOUND" <<endl;
}
else{
count = 1;
for(i=2; i<=num ;i++){
j=1;
ret = checkPrime(i);
if(ret){
cout << i;
for(;j<=count;j++)
cout << "*";
cout<<endl;
count++;
}
else{
cout << i << endl;
}
}
cout<< "Found " << count - 1 << " PRIME NUMBERS" <<endl;
}
cout << "DO YOU WANT TO TRY AGAIN (Y/N)? : ";
cin>>ch;
}
cout<< "Thank you goodbye ..." <<endl;
return 0;
}
int checkPrime(int val)
{
int i = 2;
if( val == 2)
return 1;
if( val % 2 == 0)
return 0;
while( i <= (val/2) ) // A number cannot be divisible by an another number which is more than its half.
{
if(val%i == 0)
return 0;
i++;
}
return 1;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.