In: Computer Science
isPrime Function.
A prime number is a number that is only evenly divisible by itself and 1. For example, the number 5 is prime because it can only be evenly divided by 1 and 5. The number 6, however, is not prime because it can be divided evenly by 1, 2, 3, and 6.
Write a function named isPrime, which takes an integer as an argument and returns true if the argument is a prime number, or false otherwise. The program should ask for the number in main, and pass that number to the isPrime function, returning the result as to whether this number was prime or not prime. It should then display that as console output, and ask for another number from the user (repeating until the user no longer wants to make a request).
For a bonus point, for each number the user enters, return all the prime numbers from 2 up until that number (hint, you will need an additional loop).
Validate all input. Do not use using namespace std;. Don’t forget your pre and post conditions.
Hints:
Recall that the % operator divides one number by another, and returns the remainder of the division. In an expression such as num1 % num2 , the % operator will return 0 if num1 is evenly divisible by num2 .
Program:
#include <iostream>
#include <string>
void primeNumRange(int start, int end)
{
int flag;
for (int i = start; i <= end; i++) {
if (i == 1 || i == 0)
continue;
flag = 1;
for (int j = 2; j <= i / 2; ++j) {
if (i % j == 0) {
flag = 0;
break;
}
}
if (flag == 1)
std::cout << i << " ";
}
std::cout << "\n";
}
void isPrime(int number) {
int x;
bool isPrimeNumber = true;
// 0 and 1 are not prime numbers
if (number == 0 || number == 1) {
isPrimeNumber = false;
}
else {
for (x = 2; x <= number / 2; ++x) {
if (number % x == 0) {
isPrimeNumber = false;
break;
}
}
}
if (isPrimeNumber)
std::cout << "True\n";
else
std::cout << "False\n";
std::cout << "Prime Numbers : ";
primeNumRange(2, number);
}
int main()
{
int input_num;
std::cout << "Enter -1 to exit\n";
std::cout << "Enter a number : ";
std::cin >> input_num;
while (input_num >= 0) {
isPrime(input_num);
std::cout << "Enter -1 to exit\n";
std::cout << "Enter a number : ";
std::cin >> input_num;
}
return 0;
}
Output: