A positive integer value is a prime number if it is divisible only by 1 and by i
ID: 3719354 • Letter: A
Question
A positive integer value is a prime number if it is divisible only by 1 and by itself. Write a C++ code segment to read a positive integer value greater than 2 and to output a message indicating whether it is a prime number or not. To find out whether a positive integer value n greater than 2 is a prime number, you may repeatedly divide it by i= 2, then 3, then 4, . . . , until the remainder is 0 or i*i>=n. The given value is a prime number if the remainder is not 0; otherwise, it is not a prime number.
Explanation / Answer
#include <iostream>
using namespace std;
int main()
{
int n, i;
int flag=1;
cout << "Enter a number :";
cin >> n;
if(n==1||n==-1||n==0)
cout<<"Not a prime number";
else {
for(i=2;i<=n/2;i++)
{
if(n%i==0)
{
flag=0;
break;
}
}
if (flag)
cout<<"prime number";
else
cout<<"Not a prime number";
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.