【问题标题】:Implement pow(x,n)%d with integers only. (without making use of library functions) [duplicate]仅使用整数实现 pow(x,n)%d。 (不使用库函数)[重复]
【发布时间】:2015-07-30 02:38:47
【问题描述】:

基本上,只要指数是偶数,我就会使用经典的分而治之,然后想出这个。

int mymod(int a,int b){ //returns only positive value between 0 to b-1
    return a%b<0 ? (a%b)+b : a%b;
}
int Solution::pow(int x, int n, int d) {
    if(n==0) return mymod(1,d);
    int result = 1;
    while(n>0){
        if(n%2 == 1)
            result = mymod((result * x),d);
        n = n>>1; //dividing exponent by 2, if it's even. Divide and conquer whenever exponent is even
        x = mymod(x*x,d);
    }
    return result;
}

现在我正在使用 mymod 函数来计算模数,因为正常模数给了我一个 -ve 结果,这与测试用例不符。我需要用整数来实现它。这里有一件重要的事情需要注意。溢出情况。一些测试用例有足够大的 x,当乘以时可能会溢出。 下面是这个程序应该满足的一些测试用例。

X : 0
N : 0
D : 1
expected output: 0

X : -1
N : 1
D : 20
expected output: 19

X : 71045970
N : 41535484
D : 64735492
expected output: 20805472

上面的代码满足前两个测试用例(TRIVIAL)但在最后一个测试用例失败。 OJ 也接受 Python,如果是 Python,我需要一些解释。谢谢!!

【问题讨论】:

  • 那么你的问题是什么?模幂运算是密码学中非常常见的运算。找到算法并不难,对于相当大的xnd,它会很快完成。
  • 你帖子里的OJ是什么?
  • 你的问题是什么?
  • @tuananh 我认为 Online Judge
  • Python 有一个强大的内置pow() 函数,它接受第三个参数来指定模数。而且因为它是内置的,所以它始终可用,不需要导入任何模块。

标签: python c++ algorithm pow divide-and-conquer


【解决方案1】:

排队

result = mymod((result * x),d);

result * x 中,resultx 可以和d 一样大(更准确地说是d-1),所以你需要一个可以容纳d*d 一样大的整数的数据类型。对于您的情况,这可能是long long int

另一种方法是不为ints 使用库operator*,而是通过仅使用加法的类似分治法实现手动乘法函数。这样,您将需要一种数据类型,该数据类型只能容纳与 2d 一样大的整数。

另外请注意,您不需要在主循环中每次都调用mymod。您只能在循环之前调用它一次以使x 为正(x=mymod(x,d)),然后只使用operator%

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-23
    • 1970-01-01
    • 1970-01-01
    • 2015-03-01
    • 2018-03-05
    • 1970-01-01
    • 1970-01-01
    • 2021-10-19
    相关资源
    最近更新 更多