↓快轉到主要內容
  1. LeetCode/

LeetCode 3918: Sum of Primes Between Number and Its Reverse

·1 分鐘· ·
LeetCode Medium Math Number-Theory
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: medium 第一次嘗試:2026-05-03

  • 提交紀錄:Wrong Answer → Accepted

解題思路
#

r 是 n 反轉後的數,範圍是 [min(n, r), max(n, r)]。範圍不大,逐一用試除法判斷質數,加總即可。(範圍更大時可以用埃氏篩一次算好。)

我的嘗試
#

第一版判斷質數時:

  • 用 n // i == n / i 判斷整除,這要靠浮點數,而且
  • 試除的範圍是 range(2, ceil(√n) + 1),n = 2 時會試到 i = 2,2 // 2 == 2 / 2,2 被判成合數。

例如 n = 2:反轉還是 2,答案是 2,這版回傳 0。改成先處理 2、只試奇數、用 % 判斷就 AC 了。

正確解法
#

from math import isqrt

class Solution:
    def sumOfPrimesInRange(self, n: int) -> int:
        def is_prime(x: int) -> bool:
            if x < 2:
                return False
            if x % 2 == 0:
                return x == 2
            for d in range(3, isqrt(x) + 1, 2):
                if x % d == 0:
                    return False
            return True

        r = int(str(n)[::-1])
        return sum(x for x in range(min(n, r), max(n, r) + 1) if is_prime(x))

複雜度
#

時間 O(R √R),R 是範圍的上界;空間 O(1)。

要特別避免的錯誤
#

  • 用浮點除法判斷整除。
  • 試除的上界用 ceil(√n),小的數會試到自己。用 isqrt 而且只試到 √x。

面試口說整理
#

把 n 反轉後得到範圍,逐一用試除法判斷質數再加總。試除只要到 √x、用 % 判斷整除,2 要先特判。範圍更大的話可以改用篩法。

相關文章

LeetCode 204: Count Primes
·1 分鐘
LeetCode Medium Array Math Enumeration Number-Theory
LeetCode 204 解題筆記:埃氏篩,只用質數 p 從 p² 開始把倍數劃掉,外層只要到 √n
LeetCode 3618: Split Array by Prime Indices
·1 分鐘
LeetCode Medium Math Number-Theory Sieve Array
LeetCode 3618 解題筆記:判斷的是 index 是不是質數;用埃氏篩一次算出 0..n-1 哪些是質數,比每個 index 試除快
LeetCode 3899: Angles of a Triangle
·1 分鐘
LeetCode Medium Math Geometry
LeetCode 3899 解題筆記:先用三角不等式判斷能不能組成三角形,再用餘弦定理算三個角,記得排序
LeetCode 633: Sum of Square Numbers
·2 分鐘
LeetCode Medium Two-Pointers Math Binary-Search
LeetCode 633 解題筆記:a 從 0、b 從 isqrt(c) 開始對撞;平方和太大 b 減一,太小 a 加一;注意 0 也算、a 可以等於 b、浮點數開根號的誤差
LeetCode 1401: Circle and Rectangle Overlapping
·1 分鐘
LeetCode Medium Math Geometry
LeetCode 1401 解題筆記:矩形裡離圓心最近的點,是把圓心的座標 clamp 到矩形範圍內;這個點到圓心的距離 <= 半徑就重疊
LeetCode 3824: Minimum K to Reduce Array Within Limit
·1 分鐘
LeetCode Medium Binary-Search Math
LeetCode 3824 解題筆記:對 k 二分,條件是單調的;上界至少要到 n,因為操作次數至少是 n