|
楼主 |
发表于 2013-9-5 11:41
|
显示全部楼层
一共四个关于素数的自定义函数,整合到一起了:- Function myPrime(ByVal Num, Optional k = 0) '素数字
- 'Max=2^31-1=2147483647
- If k = 0 Then myPrime = IsPrime(Num) '質素数/合数判断
- If k = -1 Then myPrime = PrimePower(Num) '素因数の冪分解
- If k = -2 Then myPrime = PrimeProduct(Num) '素因数の乗数分解
- If k = 1 Then myPrime = NxtPrime(Num) '次の素数字
- End Function
- Function PrimePower$(ByVal n&) '質因数分解1 冪分解
- Dim b&, p&
- Do Until n < b ^ 2
- b = b + IIf(b = 2, 1, 2)
- Do
- If n Mod b Then
- If p Then PrimePower = PrimePower & "*" & b & IIf(p = 1, "", "^" & p): p = 0
- Exit Do
- Else
- n = n / b: p = p + 1
- End If
- Loop
- Loop
- If PrimePower = "" Then PrimePower = "=" & n Else PrimePower = "=" & Mid(PrimePower, 2) & IIf(n = 1, "", "*" & n)
- End Function
- Function PrimeProduct$(ByVal n&) '質因数分解2 乗数分解
- Dim b&
- Do Until n < b ^ 2
- b = b + IIf(b = 2, 1, 2)
- Do
- If n Mod b Then Exit Do Else n = n / b: PrimeProduct = PrimeProduct & "*" & b
- Loop
- Loop
- If PrimeProduct = "" Then PrimeProduct = "=" & n Else PrimeProduct = "=" & Mid(PrimeProduct, 2) & IIf(n = 1, "", "*" & n)
- End Function
- Function IsPrime$(ByVal n&) '質数判断
- If n < 4 Then IsPrime = "素数": Exit Function
- If n Mod 2 Then IsPrime = "素数" Else IsPrime = "合数": Exit Function
- b& = 1: m& = Int(n ^ 0.5)
- Do
- b = b + 2: If n Mod b = 0 Then IsPrime = "合数": Exit Function
- Loop While b < m
- End Function
- Function NxtPrime&(ByVal n&) '次の質数
- Dim b&, c&
- If n Mod 2 = 0 Then NxtPrime = n - 1 Else NxtPrime = n
- b = 1
- Do
- NxtPrime = NxtPrime + 2: n = NxtPrime: c = Int(n ^ 0.5)
- Do
- b = b + 2: If n Mod b = 0 Then b = 1: Exit Do
- Loop While b < c
- Loop While b = 1
- End Function
复制代码 |
|