Forum

questions on making...
 
Notifications
Clear all

questions on making a function for counting prime number between n1 to n2

4 Posts
3 Users
0 Reactions
166 Views
(@john20091209)
Posts: 2
New Member
Topic starter
 

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

 
Posted : 08/04/2019 4:11 am
(@john20091209)
Posts: 2
New Member
Topic starter
 

anyone can help?? 

🙁

 
Posted : 08/04/2019 6:11 am
(@debaser)
Posts: 837
Member Moderator
 

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.

 
Posted : 09/04/2019 4:52 am
(@tokera)
Posts: 1
New Member
 

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.

 
Posted : 19/08/2022 8:53 am
Share: