在我要求用户输入数字后,我必须打印连续的25个素数。下面的代码确实打印了素数,但它打印出空格。我无法弄清楚如何只打印素数而不打空格。到目前为止我有这个:
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
答案 0 :(得分:0)
你只需要继续前进,只记录素数:
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