Problem 7: 10001st prime
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
I first solved this problem October 8th, 2014 in my AP Computer Science class in highschool. I do not have the original code I wrote, but I have redone the solution and included it below.
For this problem, I reused the isPrime
function I wrote for Problem 3and wrote a new function findNextPrime
that takes an integer as a parameter and returns the net greatest prime number. Then in main
I simply loop and generate prime numbers, keeping track of the number and its index, and stop when index reaches 10,001
#include <iostream>
#include <cmath>
bool isPrime(int x) {
// 1 is not prime; false for non-positive integers
if (x <= 1) return false;
// 2 is prime
else if (x == 2) return true;
else if (x % 2 == 0) return false;
else {
// iterate through all odd nums less than square root of x
for (int i = 3; i <= sqrt(x); i += 2)
// if x is divisible by a number, it is not prime
if (x % i == 0) return false;
return true;
}
}
int findNextPrime(int x) {
for (x += 1; !isPrime(x); x++);
return x;
}
int main() {
int prime = 2;
int index = 1;
while (index < 10001) {
prime = findNextPrime(prime);
index++;
}
std::cout << prime << std::endl;
}
Answer: 104743