// This program prints a list of prime numbers from // 1 to 100. #include #include bool isprime(int); int nth_prime(int n); int main() { int n; cout << "Enter n: "; cin >> n; cout << "The nth prime number is " << nth_prime(n) << endl; } // john's function: // this function determines the n'th prime number // the 1st prime number is 1 // 2nd prime number is 2 // 3rd prime number is 3 // 4th prime number is 5 // 5th prime number is 7 // 6th prime number is 11 // 'n' is the index of the prime number we want to compute // the first column of numbers in the table corresponds to 'counter' // the second column of numbers in the table corresponds to 'i' int nth_prime(int n) { int i; int counter = 0; for (i=1; counter < n ; i++) { if (isprime(i)) { counter = counter + 1; } } // must decrement i by 1 because for loop added 1 to i before exiting return i-1; } bool isprime(int p) { int i; int stopval; bool pisprime; stopval = int(sqrt(p) + .5); // DECIDE IF IT IS A PRIME pisprime = true; for (i=2; i<=stopval && pisprime; ++i) { // can p be divided by i with no remainder if (p % i == 0) pisprime = false; } return pisprime; }