今有一個四位數的整數,請問四個數字和為9的個數共有幾個 ?
程式碼參考如下(Excel VBA)
Public Sub MathNum()
Dim iith As Variant
Dim ii4 As Variant
Dim ii3 As Variant
Dim ii2 As Variant
Dim ii1 As Variant
iith = 0
For ii4 = 1 To 9
For ii3 = 0 To 9
For ii2 = 0 To 9
For ii1 = 0 To 9
If ii4 + ii3 + ii2 + ii1 = 9 Then
Debug.Print iith, ii4, ii3, ii2, ii1
iith = iith + 1
End If
Next ii1
Next ii2
Next ii3
Next ii4
End Sub
運用迴圈,對所有的四位數整數逐一搜尋檢核,找出合格符合題意條件,這個概念還可以運用在很多領域,例如A、B、C分別是介於2~5的整數,求A+B+C不大於10的組合數,對於開發型態類的交易策略,實用性很大 !