c - 为什么 spoj 对于 "Power of Integer"的解决方案给出错误答案?

标签 c algorithm

我正在尝试解决INTEGER1 spoj 上的问题。我的方法很简单。它首先计算 2 到 63 的所有幂的 x(x^i=n)。然后删除所有重复项,最后将幂相加。但它在 spoj 上给了我错误的答案。 我已经在 Ideone 和我的机器上尝试过很多用例,但它给出了正确的结果。

#include<stdio.h>
#include<math.h>
int main()
{
    unsigned long long int a,b,result;
    unsigned long long int power[65],temp;
    int i,j;

    while(1)
    {
        scanf("%lld",&a);
        scanf("%lld",&b);
        if(a==0)
            break;
        result=0;
        power[0]=0;
        power[1]=b-a+1;

        a--;
        for(i=2;i<64;i++)
        {
            power[i]=floor(pow((long double)b,(long double)1/i));
            while(pow((power[i]-1),(long double)i)>=b)
            {
                power[i]--;
            }
            while(pow((power[i]+1),(long double)i)<=b)
            {
                power[i]++;
            }

            temp=floor(pow((long double)a,(long double)1/i));
            while(pow((temp-1),(long double)i)>=a)
            {
                temp--;
            }
            while(pow((temp+1),(long double)i)<=a)
            {
                temp++;
            }
            power[i]-=temp;
        }
        for(i=63;i>=1;i--)
        {
            for(j=i*2;j<64;j=j+i)
            {
                power[i]-=power[j];
            }
        }
        for(i=1;i<64;i++)
        {
            result+=i*power[i];
        }
        printf("%lld\n",result);
    }

    return 0;
}

请帮帮我。

最佳答案

用于输入

100 100
10000 100000000
100000000000 100000000000
100000000000000 100000000000000
1000000000000000 1000000000000000
0 0

你的输出是

2
100001508
11
14
11

但正确的输出是

2
100001508
11
14
15

现在寻找akth根..做一些数学

let x = a ^ (1 / k) (^ denotes power NOT XOR)(this is also `kth` root of `a`)

两边取自然对数 (ln)

ln x = ln (a ^ (1 / k)) = (1 / k) * ln (a) {property of log}

现在两边都取指数

exp (ln x) = exp (ln (a) / k)

并根据log属性

exp (ln x) = x

所以我们终于得到了

x = exp (ln(a) / k) which is equivalent to `kth` root of `a`

这是一个在 C 中查找它的函数

请记住,在数学中,我们使用 ln 来查找自然对数,这相当于 C 中的 log

double kth_root_finder(long long int a, long long int k) {
    if (k == 1) {
         return a;
    }
    if (k == 2) {
         return sqrt(a);
    }
    return exp(log(a) / k);
}

编辑1:-正如OP指出的那样,将会出现溢出,但我不认为它会发生......考虑一个我们有的情况

a = 1000000000000000000 and k = 2 (worst case)(ignoring second if condition)

然后

exp(log(1000000000000000000) / 2) = 999999999.999999 = 1000000000(if ceil is taken)

here是上面的链接.. 所以我不认为有可能溢出..如果有请指出..

关于c - 为什么 spoj 对于 "Power of Integer"的解决方案给出错误答案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24762505/

相关文章:

c - 使用 C 语言中的函数

c - 如果 char 按标准为 1,为什么要写 `sizeof(char)`?

algorithm - 如何构造具有任何连续数字的唯一总和的正整数序列?

algorithm - 15x15像素人脸的人脸检测算法?

algorithm - 如果 m<n,O(n+m) 和 O(n) 符号是否等效?

c - 消除前导零,同时仍保持正确对齐

c - 将普通数据传递给 pthread void *

C - *x++ = *y++ 是否定义明确?

c++ - 3-sum 替代方法

C - 二维数组向外(从中心开始)顺时针螺旋遍历