How to count number of primes in a range?

Viewed 2395

I created a VBA function called prime(n) that outputs TRUE if n is a prime number or FALSE if not. It works.

Function prime(n As Integer) As Boolean
    'Place your code here
    Dim i As Integer
    prime = True

    If n = 1 Then
        prime = False
    ElseIf n > 2 Then
        For i = 2 To n - 1
            If n Mod i = 0 Then
                prime = False
                Exit Function
            End If
        Next i
    End If
End Function

I've the task to create a VBA function called counterprime(n1,n2) that counts the number of prime numbers between the integers n1 and n2 (inclusive). This function is based on the first function and according to the task I can implement a loop and a counter variable as follows:

For i = n1 to n2
    If prime(i) Then c = c + 1
Next i

How should I include this in my prime(n) function to create coutnerprime(n1,n2).

0 Answers
Related