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

Python求给定数字最近质数的代码优化求助(新手向)

Optimizing Your "Find Nearest Larger Prime" Code

Hey there! Great job getting the core functionality working—this is a fantastic first step as a new programmer. Let's break down some key improvements we can make to your code to boost efficiency, avoid potential bugs, and make it easier to read and maintain.

1. Replace Recursion with Iteration to Avoid Stack Overflow

Your current isprime function uses recursion to check the next number when it finds a composite. This works for small numbers, but if you input a large composite (like 1000000), Python will hit its default recursion depth limit and throw an error. Iteration is safer here because it doesn't build up a call stack.

2. Optimize the Primality Check

Your prime-checking logic works, but it can be made much more efficient:

  • Start checking from 2 instead of 1: Every number is divisible by 1, so we can skip it entirely.
  • Early exit: As soon as we find a divisor, we know the number isn't prime—no need to keep looping.
  • Use integer square root: Calculating int(math.isqrt(n)) is more accurate and faster than int(n**0.5) (since floating-point operations can have precision issues for large numbers).

3. Split Functions for Modularity

Right now, your isprime function does two things: checks if a number is prime and finds the next prime when it isn't. Splitting these into separate functions makes your code cleaner, reusable, and easier to debug.

4. Improve Variable Names & Readability

Short, unclear variable names like a, b, c make it hard to follow what's happening. Using descriptive names (like n, candidate, is_prime) makes your code self-documenting.


Optimized Code

import time
import math

def is_prime(n):
    """Check if a number n is a prime number."""
    if n <= 1:
        return False
    # Handle even numbers first for faster checks
    if n == 2:
        return True
    if n % 2 == 0:
        return False
    # Check odd divisors up to sqrt(n)
    max_divisor = math.isqrt(n)
    for i in range(3, max_divisor + 1, 2):
        if n % i == 0:
            return False
    return True

def find_next_prime(n):
    """Find the smallest prime number greater than or equal to n."""
    candidate = n
    while True:
        if is_prime(candidate):
            return candidate
        candidate += 1

# Example usage
start = time.time()
input_numbers = [89, 54, 36, 74, 44, 19, 12]
result = [find_next_prime(num) for num in input_numbers]
print(result)  # Output: [89, 59, 37, 79, 47, 19, 13]
stop = time.time()
print(f"Execution time: {stop - start:.8f} seconds")

Key Improvements Explained

  • is_prime function:

    • Handles edge cases (numbers ≤1, even numbers) upfront to avoid unnecessary loops.
    • Only checks odd divisors after handling even numbers, cutting the number of iterations in half.
    • Uses math.isqrt for precise integer square root calculation.
  • find_next_prime function:

    • Focuses solely on finding the next prime, making the logic easy to follow.
    • Uses a while True loop to increment the candidate until a prime is found—no recursion risk.
  • List comprehension: Replaces the for-loop + append with a concise, Pythonic way to generate the result list.

Performance Note

Your original code runs quickly for small inputs, but the optimized version will shine with larger numbers. For example, if you input 999999, the optimized prime check will skip even numbers and exit early, while the original code would loop through every divisor up to the square root (and risk recursion issues).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 07:12:50