如何找到计算 x^n 的最少操作数

发布于 2024-10-10 03:17:48 字数 526 浏览 0 评论 0原文

这是问题来自

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

药祭#氼 2024-10-17 03:17:48

请参阅: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?

陈独秀 2024-10-17 03:17:48
#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;
}
#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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文