我只是在math.stackexchange上发布了一个数学问题,但我会问这里的人们以编程方式递归算法。
问题:填写1至9的空白数字(每次空白一次且仅一次)以完成等式。
附加条件:
1. Mathematic priority DOES matter.
2. All numbers (include evaluation result) should be integers.
Which mean the divide should be divisible (E.g. 9 mod 3 = 0 is OK, 8 mod 3 != 0 is not OK).
3. For those who don't know (as one in the original question), the operations in the diagram are:
+ = plus; : = divide; X = multiple; - = minus.
答案应该超过1个。我希望有一个递归算法来找出所有解决方案。
PS:我想了解递归算法,性能改进。我试图用蛮力来解决这个问题。我的电脑冻结了很长一段时间。
答案 0 :(得分:2)
你必须找到合适的人选
9! = 362880
这不是一个很大的数字,您可以通过以下方式进行计算:
isValid(elements)
//return true if and only if the permutation of elements yields the expected result
end isValid
isValid
是验证器,用于检查给定的排列是否正确。
calculate(elements, depth)
//End sign
if (depth >= 9) then
//if valid, then store
if (isValid(elements)) then
store(elements)
end if
return
end if
//iterate elements
for element = 1 to 9
//exclude elements already in the set
if (not contains(elements, element)) then
calculate(union(elements, element), depth + 1)
end if
end for
end calculate
按以下方式致电calculate
:
calculate(emptySet, 1)
答案 1 :(得分:0)
以下是使用PARI / GP的解决方案:
div(a,b)=if(b&&a%b==0,a/b,error())
f(v)=
{
iferr(
v[1]+div(13*v[2],v[3])+v[4]+12*v[5]-v[6]-11+div(v[7]*v[8],v[9])-10==66
, E, 0)
}
for(i=0,9!-1,if(f(t=numtoperm(9,i)),print(t)))
函数f
在此定义特定函数。我使用了辅助函数div
,如果除法失败(产生非整数或除以0),则会抛出错误。
通过拆分涉及分割的块并且如果它们失败则提前中止,可以使程序更有效。但是,因为这只需要几毫秒才能完成所有9个!排列我认为不值得。