我试图在excel中创建一个函数,将所有相对质数赋予给定数字。但是,当我尝试它时,它只是用数组的第一个值填充一个单元格。
Function selectE(phi) As Variant
Dim list(999) As Variant
Dim count As Integer
count = 0
For i = 2 To phi
If WorksheetFunction.Gcd(phi, i) = 1 Then
list(count) = i
count = count + 1
End If
Next i
selectE = list()
End Function
答案 0 :(得分:0)
Function selectE(phi) As Integer()
Dim list() As Integer
Dim count As Integer
count = 0
For i = 2 To phi
If WorksheetFunction.Gcd(phi, i) = 1 Then
ReDim Preserve list(count + 1)
list(count) = i
count = count + 1
End If
Next i
selectE = list()
End Function
The above function allowed you to return an array of the primes.
However, I made some tiny edit to it:
It returns an integer array instead of a variant to make it more explicit (ie. Function selectE(phi) As Integer()
)
I didn't set the initial array size to 999 (ie. Dim list() As Integer
), I used Redim Preserve list(count + 1)
to make it increase in size dynamic to the number of primes you have in the array
So now we need a sub to call that function and then fill in the cells with the primes by iterating through the returned array. Note that we are filling in the first column and the for loop increments the row to put the value in (ie. Cells(i + 1, 1) = myarr(i)). Also note that I am just testing it for the number 1234 in selectE(1234)
, but you can do it for any number.
Sub FillInCells()
Dim myarr() as Integer
Dim i as Integer
myarr = selectE(1234)
For i = 0 to UBound(myarr) - 1
Cells(i + 1, 1).Value = myarr(i)
Next i
End Sub