Guest User

Untitled

a guest
Oct 23rd, 2018
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.98 KB | None | 0 0
  1. #include "stdafx.h"
  2. #include "iostream"
  3. #include "climits"
  4. #include "cmath"
  5. #include "array"
  6. using namespace std;
  7.  
  8.  
  9. int main()
  10. {
  11.  
  12. // declare variables to store user input
  13. int lowerBound, upperBound;
  14.  
  15. // prompt user for lesser and greater integers and store them
  16. cout << "Program to find all primes between two integers." << endl;
  17. cout << "Enter lesser integer: " << endl;
  18. cin >> lowerBound;
  19. cout << "Enter greater integer: " << endl;
  20. cin >> upperBound;
  21.  
  22. // if statement to switch the input variables if the user accidentally enters them backwards
  23. if (lowerBound > upperBound) {
  24. int temp = lowerBound;
  25. lowerBound = upperBound;
  26. upperBound = temp;
  27. }
  28.  
  29. // initialize int array with the first 5 primes
  30. int primes[100] = { 2, 3, 5, 7, 11 };
  31.  
  32. // loop to find primes between 12 and 200 (since we already have primes from 1-11 in the array)
  33. for (int i = 12; i <= 200; i++) {
  34.  
  35. // the maximum divisor needed to determine if the current integer being tested is prime
  36. double maxDivisor = sqrt(i);
  37.  
  38. // variable for the current size of the array
  39. int size = 5;
  40.  
  41. // boolean variable is set to true by default
  42. bool isPrime = true;
  43.  
  44. for (int j = 0; j <= size; j++) {
  45. int remainder = (i % primes[j]);
  46.  
  47. // once the maximum divisor is reached, there is no need to continue testing for the current integer
  48. if (primes[j] > maxDivisor) {
  49. break;
  50. }
  51.  
  52. // if the remainder of divison by a prime is 0, the number is not prime, so set the boolean variable to false
  53. if (remainder = 0) {
  54. isPrime = false;
  55. }
  56. }
  57.  
  58. // if isPrime is still true after the nested loop, the integer value being tested will be placed in the next element of the array
  59. if (isPrime == true) {
  60. primes[size] = i;
  61.  
  62. // since we added to the array, increment size by 1
  63. size++;
  64. }
  65.  
  66. }
  67.  
  68. // display the first 20 values in the array for debugging
  69. for (int k = 0; k < 20; k++) {
  70. cout << primes[k] << ", ";
  71. }
  72.  
  73. system("pause");
  74. return 0;
  75. }
Add Comment
Please, Sign In to add comment