I just created a function called prime, which is used to return True if the number is prime number and it works.
My problem is now i have to create a function called countprime number that between variable n1 to n2. I copied some coding in other forum and it works!
but i dont understand the logic behind for this countprime function, can anyone explain it to me??
What is countprime = countprime - prime(i) ??
Thanks
Option Explicit
Function prime(n As Integer) As Boolean
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
Function countprime(n1 As Integer, n2 As Integer) As Integer
Dim i As Integer
For i = n1 To n2
countprime = countprime - prime(i)
Next i
End Function
anyone can help??
🙁
Prime(i) will return True if the number i is prime. In VBA true is equivalent to -1 and False is equivalent to 0, so subtracting the result of the Prime function will either subtract 0 (no change) or subtract -1, which is the same as adding 1, so increases the count of prime numbers.
from 1 to 1000 prime number list you can copy from web, when you search "prime numbers between 1 to 1000" you will give the answers.