c - 如何降低以下循环的时间复杂度?

标签 c math time-complexity modulo

for(i=0;i<N-2;i++)
       count=(count*10)%M;

这里,N 可以达到 10^18,M 是 (10^9 +7)。因为这个循环需要 O(n) 的时间来执行,所以我在我的代码中得到了 TLE。有什么办法可以降低时间复杂度?

最佳答案

问题基本上是:

(count*a^b)%mod = ((count%mod)*((a^b)%mod))%mod

a = 10, b = 10^18

你可以找到 ((a^b)%mod) 使用:

long long power(long long x, long long y, long long p)
{
    long long res = 1;      // Initialize result

    x = x % p;  // Update x if it is more than or 
                // equal to p

    while (y > 0)
    {
        // If y is odd, multiply x with result
        if (y & 1)
            res = (res*x) % p;

        // y must be even now
        y = y>>1; // y = y/2
        x = (x*x) % p;  
    }
    return res;
}

幂函数的时间复杂度为 O(log y)。

在您的例子中,count 是一个 1 位数字,因此我们可以简单地将其与 (count%mod) 相乘,最后对结果取模。如果 count 也是一个很大的数字,并且会导致溢出,那么我们可以这样做:

long long mulmod(long long a, long long b, long long mod)
{
    long long res = 0; // Initialize result
    a = a % mod;
    while (b > 0)
    {
        // If b is odd, add 'a' to result
        if (b % 2 == 1)
            res = (res + a) % mod;

        // Multiply 'a' with 2
        a = (a * 2) % mod;

        // Divide b by 2
        b /= 2;
    }

    // Return result
    return res % mod;
}

关于c - 如何降低以下循环的时间复杂度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49768253/

相关文章:

database - 为什么哈希连接的复杂度是O(n+m)?

algorithm - 具有不同输入的串行循环的时间复杂度

time-complexity - 他们如何计算这个问题的时间复杂度

algorithm - 计算没有连续元素的子集总数

python : easy way to do geometric mean in python?

c - C语言中指向字符串的指针是什么?

c - 处理系统时间变化

c - 当值通过 C 中的多个函数时,如何更新变量?

c - "implicit declaration of function"与函数原版的区别

python - 内插数列