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

来源:互联网 时间:2016-01-03

自定义函数

=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

 

相关阅读:
Top