练习-排列组合的计算

在79个数字中找到相加等于124704的四位数

不用数组的做法

Sub t()

Dim i, j, k, l As Integer
Dim t

t = Timer

For i = 2 To 80
    For j = 2 To 80
        For k = 2 To 80
            For l = 2 To 80
                If Range("a" & i) + Range("a" & j) + Range("a" & k) + Range("a" & l) = 124704 Then
                    Range("f3") = Range("a" & i)
                    Range("g3") = Range("a" & j)
                    Range("h3") = Range("a" & k)
                    Range("i3") = Range("a" & l)
                    GoTo 10
                End If
            Next
        Next
    Next
Next

10
MsgBox Format(Timer - t, "0.00000")
End Sub

执行时间为3秒左右

使用数组的做法

Sub test()
Dim i, j, k, l As Integer
Dim t
Dim arr()

t = Timer
arr = Range("a1:a80")
For i = 2 To 80
    For j = 2 To 80
        For k = 2 To 80
            For l = 2 To 80
            
                If arr(i, 1) + arr(j, 1) + arr(k, 1) + arr(l, 1) = 124704 Then
                    Range("f3") = arr(i, 1)
                    Range("g3") = arr(j, 1)
                    Range("h3") = arr(k, 1)
                    Range("i3") = arr(l, 1)
                    GoTo 100
                End If
            Next
        Next
    Next
Next


100
MsgBox Format(Timer - t, "0.00000")

End Sub

执行时间为0.04秒

你可能感兴趣的:(练习-排列组合的计算)