Answer to Question #345235 in C++ for Ali

Question #345235

Input a positive integer from the user and determine whether the number is a prime number or not.

1
Expert's answer
2022-05-26T09:13:56-0400
#include <iostream>


int main()
{
	int num;
	std::cout << "Enter a positive integer: ";
	std::cin >> num;
	
	bool is_prime = true;
	if (num < 2)
	{
		is_prime = false; // 0 and 1 are not prime
	}
	else
	{
		for (int i = 2; i <= num / 2; ++i)
		{
			if (num % i == 0)
			{
				is_prime = false;
				break;
			}
		}
	}

	if (is_prime)
		std::cout << num << " is a prime number";
	else
		std::cout << num << " is not a prime number";

	return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS