|
可以计算任意比例数值的递归代码:
题目规则:0-9这10个数字,拆分为2组各5个不重复,组成的两个数进行除法运算,
求结果最接近目标值的那几组数。- Dim x#, k&, cnt&
- Sub test()
- x = 3.1415926535
- x = Range("f1") '可在F1单元格中任意设置小数
- k = 1: cnt = 0: [a1].CurrentRegion = ""
- Dim a(9)
- For i = 1 To 9
- If i * x > 10 Then Exit For
- a(i) = 1: Call dg(a, i, 2): a(i) = 0
- Next
- k = k - 1: [g1] = k: [g2] = cnt
- If k Then [a1].Resize(k, 4).Sort [d1], 1, , , , , , 2
- End Sub
- Sub dg(a, fm, t)
- Dim i&, j&, s&
- cnt = cnt + 1
-
- For i = 0 To 9
- If a(i) = 0 Then
- If t = 5 Then
- s1 = fm * 10 + i
- p = Round(s1 * x / 10, 0)
- ' p = Round(s1 * 0.31415926535, 0)
- If p < 10000 Then
- b = a: b(i) = 1: s = p
- For j = 1 To 4
- n = s Mod 10: If b(n) Then Exit For
- b(n) = 1: s = s \ 10
- Next
- If j = 5 Then
- For j = 0 To 9
- If b(j) = 0 Then p = p * 10 + j: Exit For
- Next
- Cells(k, 1) = p
- Cells(k, 2) = s1
- Cells(k, 3) = p / s1
- Cells(k, 4) = Abs(p / s1 - x)
- ' Cells(k, 4) = Abs(p / s1 - 3.1415926535) 'Pi=3.14159265358979
- k = k + 1
- End If
- End If
- Else
- a(i) = 1: Call dg(a, fm * 10 + i, t + 1): a(i) = 0
- End If
- End If
- Next
- End Sub
复制代码 发现,如果是求Pi的倒数=1/Pi()=0.318309886183791的近似值,
则前面5组是:
19273 60548
31062 97584
18432 57906
15720 49386
30712 96485
而和Pi()的前五组相差较大:
85910 27346
97584 31062
84531 26907
96485 30712
86190 27435
仅第2组在两边都出现。 |
|