Printing prime numbers

我的未来我决定 提交于 2020-06-18 11:42:26

问题


I have to print the sequential 25 prime numbers after I ask the user to input a number. The code below indeed does print prime numbers but it prints empty spaces. I can't figure out how to make it print ONLY the prime numbers and no empty spaces. I have this thus far:

Public Function IsPrime(value)
Dim remainder As Double
Dim rounded As Long
Dim Max As Long
Dim j As Long

IsPrime = 0                                               
Max = 1 + Int(value / 2)                         
For j = 2 To Max                                     
   rounded = Int(value / j)                     
   remainder = (value / j) - rounded   

    If remainder = 0 Then
      Exit For
    End If

Next j

If j = Max + 1 Or value = 2 Then         
  IsPrime = 1
End If

If value <= 1 Then
  IsPrime = 0
End If

End Function



Public Sub printprime()
Dim x As Integer
Dim row As Integer
Dim col As Integer
Dim j As Integer
Dim matrix1(1 To 5, 1 To 5) As Integer


x = InputBox("Please enter a number ")
j = 1
For row = 1 To 5
  For col = 1 To 5
    If IsPrime(x + j) = 1 Then
      Cells(row, col) = x + j
      matrix1(row, col) = Cells(row, col)
    End If
    j = j + 1
  Next col
Next row

回答1:


You just need to keep going and only record the primes:

Public Sub printprime()
    Dim x As Long
    Dim row As Long
    Dim col As Long
    Dim j As Long

    x = InputBox("Please enter a number ")

    row = 1
    col = 1
    For j = x + 1 To 9999
        If IsPrime(j) Then
            Cells(row, col) = j
            col = col + 1
            If col = 6 Then
                col = 1
                row = row + 1
            End If
            If row = 7 Then Exit Sub
        End If
    Next j
End Sub



来源:https://stackoverflow.com/questions/39562318/printing-prime-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!