これまでの「統計情報」に加えて、素数リストそのものも返す関数を作ってみましょう。今回は 最小値・最大値・個数・合計・平均値・中央値・素数リスト をまとめて返します。
サンプルコード
Function PrimeStatsWithList(ByVal startNum As Integer, ByVal endNum As Integer) As Variant
Dim primes() As Long
Dim i As Long, j As Long
Dim isPrime As Boolean
Dim minPrime As Long, maxPrime As Long
Dim count As Long, total As Long
Dim avg As Double, median As Double
Dim found As Boolean
' 一時配列に素数を格納
ReDim primes(1 To endNum)
count = 0
total = 0
found = False
For i = startNum To endNum
If i >= 2 Then
isPrime = True
For j = 2 To Int(Sqr(i))
If i Mod j = 0 Then
isPrime = False
Exit For
End If
Next j
If isPrime Then
count = count + 1
primes(count) = i
total = total + i
If Not found Then
minPrime = i
found = True
End If
maxPrime = i
End If
End If
Next i
' 平均値
If count > 0 Then
avg = total / count
Else
avg = 0
End If
' 中央値
If count > 0 Then
If count Mod 2 = 1 Then
median = primes((count + 1) \ 2)
Else
median = (primes(count \ 2) + primes(count \ 2 + 1)) / 2
End If
Else
median = 0
End If
' 素数リストを必要なサイズに詰め直す
Dim primeList() As Long
If count > 0 Then
ReDim primeList(1 To count)
For i = 1 To count
primeList(i) = primes(i)
Next i
End If
' 結果を配列で返す {最小値, 最大値, 個数, 合計, 平均値, 中央値, 素数リスト}
Dim result(1 To 7) As Variant
result(1) = minPrime
result(2) = maxPrime
result(3) = count
result(4) = total
result(5) = avg
result(6) = median
result(7) = primeList
PrimeStatsWithList = result
End Function
VB呼び出し例
Sub TestPrimeStatsWithList()
Dim stats As Variant
Dim primes As Variant
Dim i As Integer
stats = PrimeStatsWithList(10, 50)
MsgBox "最小の素数: " & stats(1) & vbCrLf & _
"最大の素数: " & stats(2) & vbCrLf & _
"素数の個数: " & stats(3) & vbCrLf & _
"素数の合計: " & stats(4) & vbCrLf & _
"素数の平均: " & stats(5) & vbCrLf & _
"素数の中央値: " & stats(6)
primes = stats(7)
Debug.Print "素数リスト:"
For i = LBound(primes) To UBound(primes)
Debug.Print primes(i)
Next i
End Sub
VB実行結果(10~50の場合)
- 素数リスト → 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47
- 最小値 → 11
- 最大値 → 47
- 個数 → 11
- 合計 → 311
- 平均値 → 28.27…
- 中央値 → 29
ポイント
- 統計情報と素数リストを同時に返せるので、分析とデータ利用が両立できる
stats(7)に素数リストが入っているので、ループで取り出して利用可能- 範囲を変えれば「100~200の素数リストと統計」なども簡単に取得できる
👉 この関数をさらに拡張して「素数リストをExcelシートに直接書き込む」ようにすると、データ分析にすぐ使える便利ツールになります。
