184k views
0 votes
Instructions

Write a program that prompts the user to input a positive integer. It should then output a message indicating whether the number is a prime number. (Note: An even number is prime if it is 2. An odd integer is prime if it is not divisible by any odd integer less than or equal to the square root of the number.)

1 Answer

1 vote

Answer: The c++ program to determine if the input number is prime is given below.

#include<iostream>

#include<math.h>

using namespace std;

int main() {

int num, n;

int prime=0;

int i=3;

cout<<"This program determines whether the number is prime." <<endl;

do

{

cout<<"Enter any positive number."<<endl;

cin>>num;

if(num<=0)

cout<<"Invalid input. Enter any positive number."<<endl;

}while(num<=0);

n=sqrt(num);

if((num==1)||(num==2))

{

cout<<"The input "<<num<<" is prime."<<endl;

}

else if(num%2==0)

{

cout<<"The input "<<num<<" is not prime."<<endl;

}

else

{

do

{

if(num%i == 0)

prime += 1;

i++;

}while(i<n);

if(prime>1)

cout<<"The input "<<num<<" is not prime."<<endl;

else

cout<<"The input "<<num<<" is prime."<<endl;

}

return 0;

}

OUTPUT

This program determines whether the number is prime.

Enter any positive number.

-9

Invalid input. Enter any positive number.

Enter any positive number.

0

Invalid input. Enter any positive number.

Enter any positive number.

47

The input 47 is prime.

Step-by-step explanation: This program accepts numbers beginning from 1. Any number less than 1 is considered as invalid input.

The test for prime is done using multiple if-else statements.

If number is even, it is not prime. Any number divisible by 2 is an even number. Except 2, it is even but also prime since it is divisible by itself only.

For odd numbers, number is divided by all odd numbers beginning from 3 till square root of the input. We first calculate and store square root of input.

n=sqrt(num);

An integer variable prime is initialized to 0. This variable is incremented each time the number is divisible by other number.

int prime=0;

do

{

if(num%i == 0)

prime += 1;

i++;

}while(i<n);

Since prime number is only divisible by itself, all the prime numbers undergo this condition and hence, value of prime variable becomes 1.

The 0 and 1 values of variable prime indicate prime number. Other greater values indicate input is not prime.

if(prime>1)

cout<<"The input "<<num<<" is not prime."<<endl;

else

cout<<"The input "<<num<<" is prime."<<endl;

User Elharony
by
5.9k points