首页 > Excel专区 > Excel函数 >

EXCEL自定义函数求1000以内的质数

Excel函数 2023-01-13

自定义函数

=ZS(ROW(A1))

下拉

自定义函数代码

Function ZS(s%)
Dim f As Boolean, arr(), a%, i%
ReDim Preserve arr(1)
arr(0) = 2
For i = 3 To 999 Step 2
For j = 2 To i – 1
If i Mod j = 0 Then f = True: Exit For
Next
If Not f Then
a = a + 1
ReDim Preserve arr(a)
arr(a) = i
End If
f = False
Next
ZS = arr(s – 1)
End Function

宏代码

Sub getZS()
Dim arr(), f As Boolean
ReDim Preserve arr(1)
arr(0) = 2
For i = 3 To 999 Step 2
For j = 2 To i – 1
If i Mod j = 0 Then f = True: Exit For
Next
If Not f Then
a = a + 1
ReDim Preserve arr(a)
arr(a) = i
End If
f = False
Next
[c2].Resize(a, 1) = Application.Transpose(arr)
End Sub


Copyright © 2016-2023 office学习教程网 office.tqzw.net.cn. All Rights Reserved.