You are on the Home/Other Tutorials/Project Euler/Problem 7 page
Google
Web This Site

Project Euler - Problem 7

More about Project Euler.

Problem description

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6^(th) prime is 13.

What is the 10001^(st) prime number?

Solution

Given how many of the Project Euler problems seem to deal with prime numbers, I have been writing a set of related VBA functions.  One of the functions returns all the prime numbers less than or equal to the argument.  So, I looked up the 10,000th prime number on the Internet (http://primes.utm.edu/lists/small/10000.txt).  It happens to be 104729. I adjusted my call to the function AllPrimes to return several more prime numbers.  Then, I looked up the function result to find the first number larger than the 104729, the 10,000th number.
Function AllPrimes(ByVal UpperVal As Variant) As Long()
        'Basic implementation of the Sieve of Eratosthenes
    If UpperVal < 2 Then Exit Function
    Dim AllNbrs() As Long, Rslt() As Long
    ReDim AllNbrs(UpperVal - 1)
    Dim I As Long
    For I = 3 To UpperVal Step 2
        AllNbrs(I - 1) = I
        Next I
    For I = LBound(AllNbrs) To UBound(AllNbrs)
        If AllNbrs(I) = 0 Then
        Else
            Dim J As Variant
            For J = CDec(AllNbrs(I)) ^ 2 - 1 To CDec(UBound(AllNbrs)) Step AllNbrs(I)
                AllNbrs(J) = 0
                Next J
            End If
        Next I
    ReDim Rslt(UpperVal)
    Rslt(0) = 2
    I = 1: J = LBound(AllNbrs)
    For J = LBound(AllNbrs) To UBound(AllNbrs)
        If AllNbrs(J) <> 0 Then Rslt(I) = AllNbrs(J): I = I + 1
        Next J
    ReDim Preserve Rslt(I - 1)
    AllPrimes = Rslt
    End Function