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

如何优化Python多嵌套循环脚本:提升五平方和等式求解效率

Optimizing Your 5-Term Pythagorean Equation Solver

First, let's address the biggest pain point: your nested loops create an astronomically large number of iterations (count^5). We can slash this complexity by focusing on pre-filtering candidates, avoiding redundant combinations, and moving checks as early as possible to eliminate invalid cases before doing heavy calculations.

1. Fix & Optimize Valid Candidate Generation

Your current generate_twin_primes function has two issues: it writes to a file unnecessarily (adding slow IO overhead) and uses an inefficient primality test. Let's fix both and directly generate the list of valid even numbers between twin primes:

import math
from itertools import combinations
from collections import defaultdict
import time

def is_prime(n):
    if n <= 1:
        return False
    if n == 2:
        return True
    if n % 2 == 0:
        return False
    # Only check up to sqrt(n), step by odd numbers to cut checks in half
    for i in range(3, int(math.isqrt(n)) + 1, 2):
        if n % i == 0:
            return False
    return True

def generate_valid_evens(max_prime):
    valid_evens = set()
    # Twin primes are i and i+2, so the middle even is i+1
    for i in range(2, max_prime - 1):
        if is_prime(i) and is_prime(i + 2):
            valid_evens.add(i + 1)
    # Return sorted list to ensure combinations are ordered naturally
    return sorted(valid_evens)

This is faster because:

  • We skip file IO entirely (one of the slowest operations in your original code)
  • The primality test stops at sqrt(n) and skips even numbers after checking 2
  • We use a set to avoid duplicate evens (a safe guard for edge cases)

2. Group Candidates by Digit Sum (Pre-Filter for Condition 5)

Condition 5 requires all numbers to have the same digit sum. Instead of checking this for every combination, group your valid evens by their digit sum first. This way, we only ever check combinations within the same group—eliminating millions of invalid combinations upfront.

def sum_digits(n):
    total = 0
    while n > 0:
        total += n % 10
        n = n // 10
    return total

def group_by_digit_sum(numbers):
    digit_sum_groups = defaultdict(list)
    for num in numbers:
        ds = sum_digits(num)
        digit_sum_groups[ds].append(num)
    return digit_sum_groups

3. Use Combinations to Avoid Duplicate Results

Your nested loops generate all permutations of a,b,c,d,e, leading to duplicate results (e.g., [2,4,6,8,10] and [4,2,6,8,10] are treated as separate). Instead, use itertools.combinations which generates unique, sorted combinations of 5 distinct elements. This reduces your iteration count from count^5 to C(count,5) (combination of count taken 5 at a time)—a massive reduction.

For example, if you have 100 valid evens:

  • Original loops: 100^5 = 10,000,000,000 iterations
  • Combinations: C(100,5) = 75,287,520 iterations (132x fewer!)

4. Early Validation Checks

For each combination, move checks in order of increasing cost to eliminate invalid cases as soon as possible:

  1. Calculate the sum of squares
  2. Check if the sum is a perfect square, and that f ≤ 65535
  3. Check if f is distinct from all elements in the combination
  4. Verify f's digit sum matches the group's sum (we already know a-e have the same sum)
def find_valid_sixlets(digit_sum_groups, max_f=65535):
    valid_sixlets = []
    max_f_squared = max_f ** 2

    for digit_sum, candidates in digit_sum_groups.items():
        # Skip groups with fewer than 5 candidates (can't form a 5-element combo)
        if len(candidates) < 5:
            continue
        
        for combo in combinations(candidates, 5):
            sum_sq = sum(x*x for x in combo)
            # Early exit if sum exceeds max_f squared (no need to check square root)
            if sum_sq > max_f_squared:
                continue
            
            # Use integer square root to avoid floating point precision issues
            f = math.isqrt(sum_sq)
            if f * f != sum_sq:
                continue
            
            # Ensure f is distinct from all elements in the combo
            if f in combo:
                continue
            
            # Final check: f's digit sum matches the group's sum
            if sum_digits(f) != digit_sum:
                continue
            
            # Add the valid sixlet (combo is already sorted, append f)
            valid_sixlets.append(list(combo) + [f])
    
    return valid_sixlets

5. Final Output & Execution

Put it all together, and add timing to measure the improvement:

if __name__ == "__main__":
    start_time = time.time()
    
    # Generate valid evens (twin primes up to 1000, so evens up to 1000)
    valid_evens = generate_valid_evens(1000)
    print(f"Number of valid evens: {len(valid_evens)}")
    print(f"Number of combinations to check: {math.comb(len(valid_evens), 5)}")
    
    # Group by digit sum
    digit_sum_groups = group_by_digit_sum(valid_evens)
    
    # Find valid sixlets
    valid_sixlets = find_valid_sixlets(digit_sum_groups)
    
    # Write results to file
    with open("output.txt", "w") as outfile:
        for sixlet in valid_sixlets:
            a,b,c,d,e,f = sixlet
            outfile.write(f"{a} {b} {c} {d} {e} | {f}\n")
    
    print(f"Found {len(valid_sixlets)} valid sixlets")
    print(f"--- {time.time() - start_time:.2f} seconds ---")

Additional Optimization Tips

  • Precompute Squares: For large candidate sets, precompute the square of each valid even and store it in a dictionary. This avoids recalculating squares for every combination.
  • Parallel Processing: Use multiprocessing.Pool to process each digit sum group in parallel (since groups are independent of each other).
  • Prune Candidates Early: If your candidate set is huge, filter out evens where 5*(x²) > 65535² (since the smallest sum of 5 distinct squares is at least the sum of the 5 smallest valid squares).

This optimized script should run orders of magnitude faster than your original nested loop approach, while meeting all your requirements (distinct numbers, sorted results, no duplicates, all conditions checked).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 18:12:44