fork download
  1. //Eric Bernal CS1A Chapter 6, P. 375, #21
  2. //
  3. /*******************************************************************************
  4.  * DETERMINE PRIME NUMBER
  5.  * _____________________________________________________________________________
  6.  * This program determines if a given whole number is prime.
  7.  * _____________________________________________________________________________
  8.  * INPUT
  9.  * number : The given whole number
  10.  *
  11.  * OUTPUT
  12.  * Whether the given number is prime
  13.  *
  14.  ******************************************************************************/
  15. #include <iostream>
  16. using namespace std;
  17.  
  18. // FUNCTION PROTOTYPE
  19. bool isPrime(int num);
  20.  
  21. int main() {
  22. //DATA DICTIONARY - INITIALIZE
  23. int number; // INPUT : A given whole number
  24. bool prime; // OUTPUT : Determine if a number is prime.
  25.  
  26. // Initialize Program Variables
  27. cout << "Enter a number to determine if it is prime: " << endl;
  28. cin >> number;
  29.  
  30. while (number < 1) {
  31. cout << "Please enter a number greater than 1: " << endl;
  32. cin >> number;
  33. }
  34.  
  35. // Determine If Given Number is Prime
  36. prime = isPrime(number);
  37.  
  38. if (prime) {
  39. cout << number << " is prime." << endl;
  40. } else {
  41. cout << number << " is not prime." << endl;
  42. }
  43.  
  44. return 0;
  45. }
  46.  
  47. /*****************************************************************************
  48.   * The purpose of the following function is to determine if a whole number is
  49.   * prime or not.
  50.   *****************************************************************************/
  51.  
  52. bool isPrime(int num) {
  53. bool prime = true;
  54. // 1 and N are always divisors, so check for 2 through (N-1)
  55. for (int i = 2; i < num; i++) {
  56. // May be prime IF all prior numbers AND this number are not
  57. // divisors
  58. prime = prime && ((num % i) != 0);
  59. }
  60. return prime;
  61. }
  62.  
Success #stdin #stdout 0.01s 5276KB
stdin
22
stdout
Enter a number to determine if it is prime: 
22 is not prime.