相关疑难解决方法(0)

快速计算n的方法!mod m其中m是素数?

我很好奇是否有一个很好的方法来做到这一点.我目前的代码是这样的:

def factorialMod(n, modulus):
    ans=1
    for i in range(1,n+1):
        ans = ans * i % modulus    
    return ans % modulus
Run Code Online (Sandbox Code Playgroud)

但它似乎很慢!

我也无法计算n!然后应用素数模数,因为有时n是如此之大,以至于n!明确计算是不可行的.

我也遇到过http://en.wikipedia.org/wiki/Stirling%27s_approximation,想知道这是否可以在某种程度上使用?

或者,我如何在C++中创建一个递归的,memoized函数?

algorithm math factorial modulus

43
推荐指数
4
解决办法
3万
查看次数

如何用原始类型进行模乘法

有没有办法构建例如(853467 * 21660421200929) % 100000000000007没有BigInteger库(请注意,每个数字都适合64位整数,但乘法结果不适合)?

这个解决方案效率低下:

int64_t mulmod(int64_t a, int64_t b, int64_t m) {
    if (b < a)
        std::swap(a, b);
    int64_t res = 0;
    for (int64_t i = 0; i < a; i++) {
        res += b;
        res %= m;
    }
    return res;
}
Run Code Online (Sandbox Code Playgroud)

c++ algorithm

12
推荐指数
4
解决办法
6301
查看次数

找到大数的组合值

我想找到(n选择r)大整数,我也必须找出那个数字的mod.

long long int choose(int a,int b)
{
    if (b > a)
        return (-1);
    if(b==0 || a==1 || b==a)
        return(1);
    else
    {
        long long int r = ((choose(a-1,b))%10000007+(choose(a-1,b-  1))%10000007)%10000007;
        return r;
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在使用这段代码,但我得到了TLE.如果有其他方法可以做,请告诉我.

c++ combinations

1
推荐指数
1
解决办法
3577
查看次数

标签 统计

algorithm ×2

c++ ×2

combinations ×1

factorial ×1

math ×1

modulus ×1