You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中大数乘法优化及循环求和代码时间复杂度降低方案

Optimizing the Sum of Four-Term Products

Hey, let's fix this performance issue for good! Your current loop works, but when end - start hits 1e5, iterating each term is unnecessary overhead. The real win here isn't optimizing multiplication (like the Russian Peasant technique)—it's replacing the entire loop with a constant-time mathematical calculation using polynomial expansion and power sum formulas.

The Core Insight

Each term (A+j)*(B+j)*(C+j)*(D+j) is a 4th-degree polynomial in j. Instead of summing each term one by one, we can:

  1. Expand the polynomial into standard form: x⁴ + c₃x³ + c₂x² + c₁x + c₀ (where x = j)
  2. Compute the sum of each power term (x⁴, x³, ..., 1) over the range j = start-1 to j = end-1
  3. Multiply each sum by its corresponding coefficient and combine everything modulo 1e9+7

Step 1: Expand the Polynomial

First, calculate the coefficients of the expanded polynomial (all modulo 10^9+7 to prevent overflow):

  • c₄ = 1 (coefficient of x⁴)
  • c₃ = A + B + C + D
  • c₂ = AB + AC + AD + BC + BD + CD
  • c₁ = ABC + ABD + ACD + BCD
  • c₀ = A*B*C*D

Step 2: Sum Power Terms Efficiently

To compute sums like sum(x⁴) from x=a to x=b (where a = start-1, b = end-1), we use closed-form formulas. Since we're working modulo a prime (1e9+7), division becomes multiplication by the modular inverse.

Here are the formulas (all calculations modulo 10^9+7):

  • Sum of 1s: sum₀ = (b - a + 1) % MOD
  • Sum of x: Replace division by 2 with multiplication by pow(2, MOD-2, MOD) (the modular inverse of 2)
  • Sum of x²: Use the inverse of 6 (pow(6, MOD-2, MOD)) for division
  • Sum of x³: Leverage the identity that the sum of cubes equals the square of the sum of integers
  • Sum of x⁴: Use the formula sum₄(n) = n(n+1)(2n+1)(3n²+3n-1)/30, with the inverse of 30 (pow(30, MOD-2, MOD))

Step 3: Put It All Together in Code

Here's the optimized Python code:

MOD = 10**9 + 7

def compute_sum(A, B, C, D, start, end):
    a = start - 1
    b = end - 1
    
    # Precompute modular inverses once
    inv2 = pow(2, MOD-2, MOD)
    inv6 = pow(6, MOD-2, MOD)
    inv30 = pow(30, MOD-2, MOD)
    
    # Helper to calculate sum of x from 1 to n
    def sum_x(n):
        if n < 0:
            return 0
        return n * (n + 1) % MOD * inv2 % MOD
    
    # Helper to calculate sum of x² from 1 to n
    def sum_x2(n):
        if n < 0:
            return 0
        return n * (n + 1) % MOD * (2 * n + 1) % MOD * inv6 % MOD
    
    # Helper to calculate sum of x⁴ from 1 to n
    def sum_x4(n):
        if n < 0:
            return 0
        term = n * (n + 1) % MOD
        term = term * (2 * n + 1) % MOD
        quad = (3 * n * n % MOD + 3 * n - 1) % MOD
        term = term * quad % MOD
        return term * inv30 % MOD
    
    # Calculate sums over the range [a, b]
    sum0 = (b - a + 1) % MOD
    sum1 = (sum_x(b) - sum_x(a - 1)) % MOD
    sum2 = (sum_x2(b) - sum_x2(a - 1)) % MOD
    sum3 = (sum_x(b) ** 2 - sum_x(a - 1) ** 2) % MOD
    sum4 = (sum_x4(b) - sum_x4(a - 1)) % MOD
    
    # Compute polynomial coefficients (mod MOD)
    c4 = 1
    c3 = (A + B + C + D) % MOD
    c2 = (A*B + A*C + A*D + B*C + B*D + C*D) % MOD
    c1 = (A*B*C + A*B*D + A*C*D + B*C*D) % MOD
    c0 = (A*B*C*D) % MOD
    
    # Combine all terms into the final total
    total = (
        c4 * sum4 % MOD +
        c3 * sum3 % MOD +
        c2 * sum2 % MOD +
        c1 * sum1 % MOD +
        c0 * sum0 % MOD
    ) % MOD
    
    # Ensure non-negative result after subtraction operations
    return total if total >= 0 else total + MOD

# Example usage:
# print(compute_sum(1, 2, 3, 4, 1, 100000))

Why This Is Way Faster

Instead of looping up to 1e5 times, this code runs in O(1) time—no matter how large the interval between start and end is. All operations are simple arithmetic with precomputed inverses, eliminating the overhead of repeated multiplications and loop iterations. This will outperform any loop-based approach by orders of magnitude.

内容的提问来源于stack exchange,提问作者Manish

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 21:54:09