text1输入数字总个数;text2输入每组的数字个数;app.path & “\1.txt”用于看输出结果;label1用于显示组个数;command1就是执行按钮。这是一个穷举组合结果的万能代码。
option explicit
private mlngallnumcount as long, mlnggetnumcount as long
private mblncancelproc as boolean, mlngcurresultcount as long
private mastroneresult() as string
private mlngfileno as long
private sub listnum(byval start as long, byval level as long)
dim i as long
if mblncancelproc then exit sub
for i = start to mlngallnumcount – mlnggetnumcount + level
mastroneresult(level) = i
if level < mlnggetnumcount then 是否到了最底层
listnum i + 1, level + 1 没到底,递归啦,这是本过程的核心,很简单哟
else
print #mlngfileno, join(mastroneresult, vbtab) 递归到最深层,就可以输出了
mlngcurresultcount = mlngcurresultcount + 1
if mlngcurresultcount mod &h2000& = 0 then
label1.caption = mlngcurresultcount 显示实际找出了多少组数字
doevents
end if
end if
next
end sub
private sub command1_click()
dim t as single, i as long
if command1.caption = “处理” then
mlngallnumcount = text1.text 数字总个数
mlnggetnumcount = text2.text 每组要取的数字个数
i = zhuhe(mlngallnumcount, mlnggetnumcount)
if i = 0 then
msgbox “结果太多,请不要尝试了!”
exit sub
end if
label2.caption = i
t = timer
mblncancelproc = false
command1.caption = “停止”
mlngcurresultcount = 0 已产生出的组合总数
redim mastroneresult(1 to mlnggetnumcount)
mlngfileno = freefile
open app.path & “\1.txt” for output as #mlngfileno
listnum 1, 1
close #mlngfileno
label1.caption = mlngcurresultcount
command1.caption = “处理”
me.caption = timer – t
else
mblncancelproc = true
end if
end sub
private function zhuhe(allnum as long, getnum as long) as long
算组合总数的过程,为防溢出,而做了特别设计
只要结果总数在20亿以内,都不会溢出的
太大的数不太可能会完成穷举,本程序也就不做尝试了
接近溢出的上限列举:65536取2、2345取3、477取4、193取5、110取6
75取7、58取8、49取9、40取10、39取11、37取12、35取13、34取15、33取16等
dim i as long, j as long, colget as collection
dim m as long, n as long, num1 as long, num2 as long
on error goto fail
num1 = 1
set colget = new collection
for i = getnum to 2 step -1
colget.add i
next
for i = allnum to allnum – getnum + 1 step -1
m = colget.count
if m > 0 then
n = m
for j = 1 to m
if j > n then exit for
if num1 mod colget(j) = 0 then
num1 = num1 \ colget(j)
colget.remove j
n = n – 1
j = j – 1
end if
next
end if
num2 = i
m = colget.count
if m > 0 then
n = m
for j = 1 to m
if j > n then exit for
if num2 mod colget(j) = 0 then
num2 = num2 \ colget(j)
colget.remove j
n = n – 1
j = j – 1
end if
next
end if
num1 = num1 * num2 分子中的两个乘数分别消去分母再相乘,可防中间过程的溢出
next
zhuhe = num1
exit function
fail:
end function
private sub form_load()
command1.caption = “处理”
end sub
private sub form_unload(cancel as integer)
mblncancelproc = true
end sub