Re: [VB2005][心得] 關於1-1000的質數

看板Visual_Basic作者時間15年前 (2008/09/27 03:11), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串3/5 (看更多)
※ 引述《keria (住左住右超好看)》之銘言: <恕刪> : 記得之前上數學課時, : 有提到求質數的方式, : 就是小於該數的平方根的質數無法整除時, : 它也會是個質數。 : 基於此概念, : 寫了一個如下的程式, : 請在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~輸入數的所有質數。 先抱歉翻這麼舊的文出來發問 我做的方法是 ===程式段開始=== Module Module1 Sub Main() Dim input, temp, n, k, s, x, count As Integer Dim array(100, 0) s = 0 count = 0 Console.Write("請輸入一個2~10000的整數 ") input = Console.ReadLine For temp = 2 To input k = 0 For n = 2 To 100 If n < temp And temp Mod n = 0 Then k += 1 array(s, 0) = temp s += 1 End If Next If k = 1 Then count += 1 End If Next Console.WriteLine("所包含的質數有") For x = 0 To s Step 1 Console.WriteLine(x, 0) Next Console.WriteLine("共" & count & "個") Console.ReadKey() End Sub End Module ====程式段結束=== 須做出輸入1~10000的數 得出所輸入的數的所有質數 並計共有幾個質數 綠字為計次部份 紅字為求質數部份 我寫的 計次部份沒有問題 可是求質數部份 怎麼跑都不對 能某請大大們替我解答一下 哪裡錯了? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 220.143.39.127 ※ 編輯: xtimer 來自: 220.143.39.127 (09/27 03:12)
文章代碼(AID): #18tJFRxn (Visual_Basic)
討論串 (同標題文章)
文章代碼(AID): #18tJFRxn (Visual_Basic)