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