「指定範囲の素数の平均値を返す関数」を作ってみましょう。今回は 開始値と終了値を引数に渡して、その範囲内の素数の平均値を返す関数です。
サンプルコード
Function AvgPrimesInRange(ByVal startNum As Integer, ByVal endNum As Integer) As Double
Dim i As Integer, j As Integer
Dim isPrime As Boolean
Dim total As Long
Dim count As Long
total = 0
count = 0
For i = startNum To endNum
If i >= 2 Then
isPrime = True
' 2から√iまでで割り切れるかチェック
For j = 2 To Int(Sqr(i))
If i Mod j = 0 Then
isPrime = False
Exit For
End If
Next j
If isPrime Then
total = total + i
count = count + 1
End If
End If
Next i
' 素数が1つもなければ0を返す
If count = 0 Then
AvgPrimesInRange = 0
Else
AvgPrimesInRange = total / count
End If
End Function
VB呼び出し例
Sub TestAvgPrimes()
Dim result As Double
result = AvgPrimesInRange(10, 50)
MsgBox "10~50の素数の平均値は " & result
End Sub
VB実行結果
- 10~50の素数は 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47
- 合計は 311、個数は 11
- 平均値は 311 ÷ 11 = 28.27…
ポイント
- 戻り値の型は
Doubleにして小数も扱えるようにする - 素数が存在しない範囲では「0」を返すようにして安全に設計
- 範囲を変えれば「100~200の素数の平均値」なども簡単に計算可能
👉 この関数を応用すれば「素数の最大値・最小値を返す関数」や「素数の一覧を返す関数」と組み合わせて、さらに便利なツールにできます。
