24. 99.おまけ 素因数分解サンプル
'素因数分解のサンプルコードです。
'Sub Main が、素数一覧の作成、
'sub SoInsuuBunkai が、素因数分解の処理になります。
Option VBASupport 1
REM ***** BASIC *****
Option Explicit
Sub Main
MsgBox("Start")
Dim max As Long
max = 1000000
Dim known(max) As Long
known(0) = 2
Dim ii As Long
ii = 0
Dim isPrime(max) As Boolean
Dim s As String
Dim i, j, lll As Long
'初期化
For i = 2 To max
isPrime(i) = True
Next
'素数個分
For i = 0 To ii
if i <= ii Then
For j = 2 To max \ known(i)
isPrime(known(i) * j) = False
Next
End if
if i = ii Then
For lll = known(i)+ 1 to max
If isPrime(lll) Then
ii = ii + 1
known(ii) = lll
Exit For
End if
Next
End if
Next
ii = 0
For i = 2 To max
If isPrime(i) Then
Cells(ii + 1, 1) = i
ii = ii + 1
End if
Next
MsgBox("End")
End Sub
sub SoInsuuBunkai
dim x as long
dim i as long
dim waru as long
dim str as string
'MsgBox("Start")
str = ""
x = Cells(10,10)
for i = 1 to 300000
waru = val(Cells(i,1))
if waru = 0 then
exit for
end if
if (x = waru) then
str = str & "*" & waru
exit for
end if
if (x mod waru) = 0 then
' msgbox waru
str = str & "*" & waru
x = x / waru
i = i - 1
endif
if (x < waru) then
msgbox "Error"
exit for
endif
next i
Cells(10,11) = "'=" & mid(str,2)
'MsgBox("End")
end sub
前へ / 次へ