Write a program that asks the user for a positive integer, N. The program then t
ID: 3882938 • Letter: W
Question
Write a program that asks the user for a positive integer, N. The program then tests if the integer is prime and writes out its result. A number is prime if it cannot be divided evenly by any number other than 1 and itself. So you will need a counting loop that starts at two and attempts to divide the number for each value of the loop counter until the number is divided evenly or the limit is reached.
For the upper limit of the loop use the number divided by two. Search Internet for mod or rem matlab functions. Use only integer arithmetic. Test your program with the number 13,249 which is prime and with 13,245 which is not prime.
Explanation / Answer
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
int number, count=0;
cout<<" Enter an Positive Integer: ";
cin>>number;
for( int i = 2; i <= number/2; i++)
{
if(number % i == 0)
{
count++;
}
}
if(count == 0)
{
cout<<endl;
cout<<number <<" is a Prime Number";
}
else
{
cout<<endl;
cout<<number <<" is not a Prime Number";
}
}
OUTPUT
Enter an Positive Integer: 13245
13245 is not a Prime Number
Enter an Positive Integer: 13249
13249 is a Prime Number
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.