In: Computer Science
Write a c++ program that prints the count of all prime numbers between A and B (inclusive), where A and B are defined as follows:
A = Any 5 digit unique number
B = A + 1000
Just a recap on prime numbers: A prime number is any number, greater or equal to 2, that is divisible ONLY by 1 and itself. Here are the first 10 prime numbers: 2, 5, 7, 11, 13, 17, 19, 23, and 29.
Rules:
You should first create a boolean function called isPrime and use that function in your program. This function should take in any int and return true if the number is prime, otherwise, return a false. In the main body of your program, you should create a loop from A to B (inclusive) and use isPrime function to determine if the loop number should be counted or not.
Your program SHOULD NOT PRINT the individual prime numbers. You can print them for your own testing purpose, but in the final submission, comment out such print statements.
Your program SHOULD ONLY PRINT the answer -- which is a number.
I WROTE THE CODE ALONG WITH THE COMMENTS
CODE:
#include <iostream>
using namespace std;
bool isPrime(int num)
{
//variables declaration.
int i=2,count=0;
for(i=2;i<num;i++)
{
if(num%i==0) //condition number is divisible or not
count++;
}
if(count==0) //count == 0 means number is prime.
return true;
else
return false;
}
int main()
{
//variables declaration.
int A,B,i,count=0;
cout<<"Enter five digit number: ";
cin>>A; //scan A.
B=A+1000;
for(i=A;i<=B;i++) //for loop used to take each number form A to
B.
{
if(isPrime(i)) //calling the function isPrime it returns true
{
count++; //increment count value
}
}
cout<<count<<" prime numbers between
"<<A<<" and "<<B;
return 0;
}
OUTPUT:
SCREENSHOT OF THE CODE: