fork download
  1. // Nicolas Ruano CS1A Chapter 6, P. 375, #21
  2. /*******************************************************************************
  3. * VERIFY IF A GIVEN NUMBER IS A PRIME NUMBER.
  4.  
  5. * ______________________________________________________________________________
  6.  
  7. * The program prompts the user for a number, ensures it’s
  8. * greater than 1, then checks if it is divisible by any number
  9. * from 2 to (number – 1). If so, it’s not prime; if not, it’s
  10. * prime. The result is then displayed.
  11.  
  12. * Computation is based on the formula:
  13.  
  14. * For a number n:
  15. * Prime(n)=
  16. * False, if n≤1,
  17. * False, if there exists an i such that 2≤i<n and n  mod  i=0,
  18. * True, Otherwise
  19.  
  20. * Where:
  21. * n  mod  i = 0 means “n is evenly divisible by i.”
  22.  
  23. * ______________________________________________________________________________
  24.  
  25. * INPUT
  26. * num int The number entered by user.
  27. *
  28. *
  29. * OUTPUT
  30. * isPrime(num) bool Control which message is printed
  31. * num int The number entered by user.
  32. *******************************************************************************/
  33. #include <iostream> // Needed for input and output
  34. using namespace std;
  35.  
  36. // Function to check if a number is prime
  37. bool isPrime(int number) {
  38. if (number <= 1) {
  39. return false; // Numbers less than or equal to 1 are not prime
  40.  
  41. }
  42.  
  43. // Check for factors between 2 and number - 1
  44. for (int i = 2; i < number; i++) {
  45. if (number % i == 0) {
  46. return false; // Found a divisor, so it's not prime
  47.  
  48. }
  49. }
  50.  
  51. return true; // No divisors found, it's prime
  52. }
  53.  
  54. int main() {
  55. int num;
  56.  
  57. cout << "Enter a number: ";
  58. cin >> num;
  59.  
  60. if (isPrime(num)) {
  61. cout << num << " is a prime number." << endl;
  62. } else {
  63. cout << num << " is not a prime number." << endl;
  64. }
  65.  
  66. return 0;
  67. }
Success #stdin #stdout 0.01s 5312KB
stdin
Standard input is empty
stdout
Enter a number: 32766 is not a prime number.