如何找到计算 x^n 的最少操作数
这是问题来自
ACM国际学院 编程大赛亚洲区域赛 比赛,横滨,2006-11-05
从 x 开始,反复乘以 x
,我们可以通过 30 次乘法来计算 x^31
:
x^2 = x * x, x^3 = x^2 * x, x^6 = x^3 * x^3, x^7 = x^6 *x, x^14 = x^7 * x^7 ,
x^15 = x^14 * x, x^30 = x^15 * x^15 , x^31 = x^30 * x
编写一个程序来找到最小的数字计算x^n
的操作 对于给定的正整数 n
,通过从 x
开始的乘法和除法,
对于 n = 31 的 n<=200
,最少的#操作是 6 < br> 对于 n = 50,最少 #operations 是 7
欢迎任何想法。
here is the problem from
ACM International Collegiate
Programming Contest Asia Regional
Contest, Yokohama, 2006-11-05
Starting with x and repeatedly multiplying by x
, we can compute x^31
with thirty multiplications:
x^2 = x * x, x^3 = x^2 * x, x^6 = x^3 * x^3, x^7 = x^6 *x, x^14 = x^7 * x^7 ,
x^15 = x^14 * x, x^30 = x^15 * x^15 , x^31 = x^30 * x
write a program to find the least number of operations to compute x^n
by multiplication and division starting with x
for the given positive integer n
and n<=200
for n = 31 the least #operations is 6
for n = 50 the least #operations is 7
Any ideas are welcome.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请参阅:http://en.wikipedia.org/wiki/Addition-chain_exponentiation
没有有效的算法可以让您获得最少的步骤数,并且动态规划不起作用。
我猜测 n 足够小,足以允许暴力解决方案通过,尽管它可能需要优化。你知道如何暴力破解吗?
See this: http://en.wikipedia.org/wiki/Addition-chain_exponentiation
There is no efficient algorithm that will get you the minimum number of steps, and dynamic programming does not work.
I am guessing that
n
is small enough to allow a brute force solution to pass, although it might need to be optimized. Do you know how to brute force it?