Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "stdafx.h"
- #include "iostream"
- #include "climits"
- #include "cmath"
- #include "array"
- using namespace std;
- int main()
- {
- // declare variables to store user input
- int lowerBound, upperBound;
- // prompt user for lesser and greater integers and store them
- cout << "Program to find all primes between two integers." << endl;
- cout << "Enter lesser integer: " << endl;
- cin >> lowerBound;
- cout << "Enter greater integer: " << endl;
- cin >> upperBound;
- // if statement to switch the input variables if the user accidentally enters them backwards
- if (lowerBound > upperBound) {
- int temp = lowerBound;
- lowerBound = upperBound;
- upperBound = temp;
- }
- // initialize int array with the first 5 primes
- int primes[100] = { 2, 3, 5, 7, 11 };
- // loop to find primes between 12 and 200 (since we already have primes from 1-11 in the array)
- for (int i = 12; i <= 200; i++) {
- // the maximum divisor needed to determine if the current integer being tested is prime
- double maxDivisor = sqrt(i);
- // variable for the current size of the array
- int size = 5;
- // boolean variable is set to true by default
- bool isPrime = true;
- for (int j = 0; j <= size; j++) {
- int remainder = (i % primes[j]);
- // once the maximum divisor is reached, there is no need to continue testing for the current integer
- if (primes[j] > maxDivisor) {
- break;
- }
- // if the remainder of divison by a prime is 0, the number is not prime, so set the boolean variable to false
- if (remainder = 0) {
- isPrime = false;
- }
- }
- // if isPrime is still true after the nested loop, the integer value being tested will be placed in the next element of the array
- if (isPrime == true) {
- primes[size] = i;
- // since we added to the array, increment size by 1
- size++;
- }
- }
- // display the first 20 values in the array for debugging
- for (int k = 0; k < 20; k++) {
- cout << primes[k] << ", ";
- }
- system("pause");
- return 0;
- }
Add Comment
Please, Sign In to add comment