fork download
  1. //Matthew Santos CS1A Ch. 6, Pg. 375, #21
  2. /***********************************************
  3.  *
  4.  * DETERMINE IF PRIME
  5.  * _____________________________________________
  6.  * Determines if any given number is prime or
  7.  * not.
  8.  * _____________________________________________
  9.  * INPUT
  10.  * num : number entered
  11.  *
  12.  * OUTPUT
  13.  * true or false (prime or not)
  14.  ***********************************************/
  15. #include <iostream>
  16. using namespace std;
  17.  
  18. // Function to check if a number is prime
  19. bool isPrime(int);
  20.  
  21. int main() {
  22.  
  23. //Declare and get input
  24. int num;
  25.  
  26. cout << "Enter a number to check if it’s prime: ";
  27. cin >> num;
  28.  
  29. //Determine is prime or not
  30. if (isPrime(num))
  31. cout << num << " is a prime number." << endl;
  32. else
  33. cout << num << " is not a prime number." << endl;
  34.  
  35. return 0;
  36. }
  37.  
  38. bool isPrime(int number)
  39. {
  40. if (number <= 1)
  41. return false; // 0, 1, and negatives are not prime
  42.  
  43. for (int i = 2; i * i <= number; i++) {
  44. if (number % i == 0)
  45. return false; // Found a divisor, not prime
  46. }
  47.  
  48. return true; // No divisors found, it's prime
  49. }
Success #stdin #stdout 0.01s 5320KB
stdin
8
stdout
Enter a number to check if it’s prime: 8 is not a prime number.