【问题标题】:how to find the least number of operations to compute x^n如何找到计算 x^n 的最少操作数
【发布时间】:2011-05-31 18:00:13
【问题描述】:

这是来自

的问题

ACM 国际学院 亚洲区编程大赛 比赛,横滨,2006-11-05

从 x 开始,反复乘以 x,我们可以计算出 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 对于给定的正整数nn<=200,通过以x 开头的乘法和除法

对于 n = 31,最少 #operations 是 6
对于 n = 50,最少的 #operations 是 7

欢迎提出任何想法。

【问题讨论】:

标签: algorithm dynamic-programming np-complete


【解决方案1】:
#include<stdio.h>
long long int pow(long long int, long long int);
int count=0;

int main()
{
    long long int a,b;
    printf("Input: ");
    scanf("%lld %lld",&a,&b);
    pow(a,b);
    printf("%d",count);
    return 0;
}

long long int pow(long long int a, long long int b)
{
    count++;
    if(b==0)
    return 1;
    long long int res=pow(a,b/2);
    if(b%2)
    return res*res*a;
    else
    return res*res;
}

【讨论】:

    【解决方案2】:

    看到这个:http://en.wikipedia.org/wiki/Addition-chain_exponentiation

    没有有效的算法可以让您获得最少的步数,动态规划也行不通。

    我猜n 足够小,可以通过蛮力解决方案,尽管它可能需要优化。你知道如何暴力破解吗?

    【讨论】:

    • +1 哦,闪亮!我想我今天已经学到了我的“新事物”。可惜它是 NP-complete :(
    • 是的,我想很多人今天会学到一些有趣的东西:) +1 也
    • 因为它是 NP 完备的,并且 n 的域相当小,编译一个表,然后进行查找...
    • 我不认为找到 single 指数的最短链的 NP-Hardness 是已知的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-04
    • 2021-07-28
    • 2020-06-12
    • 2023-02-10
    • 2017-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多