通过3次加/减和3次移位操作实现乘法849 我已经解决了4个添加和4个add / sub,我怎样才能进一步减少它?849 * X = X<<< 10-X<< 7-X<< 6 + X<<< 4+ X
答案 0 :(得分:1)
这是解决方案。请注意,您必须使用中间变量a
,否则这是不可能的。它使用:
a = (X << 4) + X
return (a << 6) + a - (X << 8)
我是通过使用答案末尾的代码在堆栈计算机上搜索可能的程序找到的。解决方案以堆栈程序的形式给出,我手动将其转换为上面的表达式:
['push X', '<<4', 'push X', '+', 'dup 0', '<<6', '+', 'push X', '<<8', '-']
这是程序......运行需要几分钟。
import heapq
def moves(adds, shifts, stack, just_shifted):
if len(stack) and shifts and not just_shifted:
for shv in xrange(1, 10):
yield (adds, shifts-1), '<<%d' % shv, stack[:-1] + [stack[-1] << shv]
if len(stack) <= adds:
for i in xrange(len(stack)):
if stack[i] != 1:
yield (adds, shifts), 'dup %d' % i, stack + [stack[i]]
if len(stack) > 1 and adds:
yield (adds-1, shifts), '+', stack[:-2] + [stack[-2] + stack[-1]]
yield (adds-1, shifts), '-', stack[:-2] + [stack[-2] - stack[-1]]
if len(stack) <= adds:
yield (adds, shifts), 'push X', stack + [1]
def find(target):
work = []
heapq.heappush(work, (0, [], 3, 3, []),)
while work:
it = heapq.heappop(work)
print it
if len(it[1]) == 1 and it[1][-1] == target:
return it[4]
just_shifted = len(it[4]) and ('<<' in it[4][-1])
for nsum, desc, nst in moves(it[2], it[3], it[1], just_shifted):
nit = (it[0]+1, nst, nsum[0], nsum[1], it[4] + [desc])
heapq.heappush(work, nit)
print find(849)