Re: [VB2005][心得] 關於1-1000的質數
<恕刪>
記得之前上數學課時,
有提到求質數的方式,
就是小於該數的平方根的質數無法整除時,
它也會是個質數。
基於此概念,
寫了一個如下的程式,
請在VB.Net(2003)的Application中,
程式使用一個TextBox、Button、ListBox:
===程式段開始===
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim aryPrime(0) As Double
Dim sqrtNum As Double
Dim Index1 As Double, Index2 As Double
aryPrime(0) = 2
For Index1 = 3 To CDbl(TextBox1.Text)
sqrtNum = Fix(Math.Sqrt(Index1))
For Index2 = 0 To UBound(aryPrime)
If aryPrime(Index2) <= sqrtNum Then
If (Index1 Mod aryPrime(Index2)) = 0 Then
Exit For
End If
Else
If Index2 = UBound(aryPrime) Then
ReDim Preserve aryPrime(UBound(aryPrime) + 1)
aryPrime(UBound(aryPrime)) = Index1
Exit For
End If
End If
Next Index2
Next Index1
ListBox1.Items.Clear()
For Index1 = 0 To UBound(aryPrime)
ListBox1.Items.Add(aryPrime(Index1))
Next
End Sub
===程式段結束===
其中,TextBox輸入一個大於3的數,
它就會在ListBox中列出1~輸入數的所有質數。
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 218.160.53.1
推
08/09 22:42, , 1F
08/09 22:42, 1F
推
08/09 22:45, , 2F
08/09 22:45, 2F
推
08/09 22:47, , 3F
08/09 22:47, 3F
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 2 之 5 篇):