一道趣味数学题

题目:

将+,-,*,/ 添加到 1,2,3,4,5,6,7,8,9 之间,使其构成的算式四则运算结果等于100,如:1*2*3*4+5+6+7*8+9=100

分析:

以上算式相当于把1~9 9 个数字和 8个(+,-,*,/ )作一个特殊顺序的排列,共有4^8=65536 种可能,再从中进行取舍。

代码:

Option Explicit
Private Declare Function EbExecuteLine Lib "vba6.dll" (ByVal pStringToExec As Long, ByVal Unknownn1 As Long, ByVal Unknownn2 As Long, ByVal fCheckOnly As Long) As Long ' API

Private Function ExecuteLine(sCode As String, Optional fCheckOnly As Boolean) As Boolean
ExecuteLine = EbExecuteLine(StrPtr(sCode), 0&, 0&, Abs(fCheckOnly)) = 0
End Function


Private Function result(ByVal x As String) As Single '计算表达式的结果
ExecuteLine "dim x as single"
ExecuteLine "x= " & x
ExecuteLine "clipboard.settext x" '发送到剪切板
result = Clipboard.GetText '从剪切板获取
Clipboard.Clear '清空剪切板
End Function

Sub main() '开始计算
getall 100
End Sub

Private Sub getall(ByVal theresult As Integer)
Dim temp As Long '四进制转换中间变量
Dim x(8) As String '获得8个位置四则运算符
Dim op(3) As String '定义四个四则运算符
Dim i As Long, j As Integer '循环变量
Dim out As String '最终表达式
Dim all As Long, num As Integer '循环范围和输出计数
num = 0
op(0) = "+"
op(1) = "-"
op(2) = "*"
op(3) = "/"

all = 4 ^ 8 - 1

For i = 0 To all
temp = i
x(0) = "1.0"
For j = 1 To 8
x(j) = op(temp Mod 4) & Format(j + 1, "0.0")
temp = temp \ 4
Next
out = Join(x, "")
If result(out) = theresult Then '条件判断
num = num + 1
Debug.Print "解 " & num & ":" & vbTab & Replace(out, ".0", "") & "=" & theresult
End If
Next
If num = 0 Then Debug.Print "无解!"
If num > 0 Then Debug.Print "共 " & num & " 组解!"
End Sub

输出:

解 1: 1*2*3*4+5+6+7*8+9=100
解 2: 1-2+3*4*5+6*7+8-9=100
解 3: 1-2+3*4*5-6+7*8-9=100
解 4: 1+2+3+4+5+6+7+8*9=100
解 5: 1*2*3+4+5+6+7+8*9=100
解 6: 1-2*3+4*5+6+7+8*9=100
解 7: 1+2*3+4*5-6+7+8*9=100
解 8: 1-2*3-4+5*6+7+8*9=100
解 9: 1+2-3*4+5*6+7+8*9=100
解 10: 1+2*3*4*5/6+7+8*9=100
解 11: 1*2*3*4+5+6-7+8*9=100
解 12: 1-2*3-4-5+6*7+8*9=100
解 13: 1+2-3*4-5+6*7+8*9=100
解 14: 1+2+3-4*5+6*7+8*9=100
解 15: 1*2*3-4*5+6*7+8*9=100
共 15 组解!

你可能感兴趣的:(J#)