Smallest Value After Replacing With Sum of Prime Factors — LeetCode 2507 Python Solution
MediumMathNumber TheorySimulation
- Problem
- #2507
- Pattern
- Math and Number Theory
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You are given a positive integer n. Continuously replace n with the sum of its prime factors.
Example
- Input
- n = 15
- Output
- 5
- Explanation
- Initially, n = 15.
Python solution
Python
class Solution:
def smallestValue(self, n: int) -> int:
while 1:
t, s, i = n, 0, 2
while i <= n // i:
while n % i == 0:
n //= i
s += i
i += 1
if n > 1:
s += n
if s == t:
return t
n = sComplexity
| Measure | Complexity |
|---|---|
| Time | O(\sqrt{n}) |
| Space | O(1) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 2507. Smallest Value After Replacing With Sum of Prime Factors is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math and Number Theory.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2507. Smallest Value After Replacing With Sum of Prime Factors?
- LeetCode 2507. Smallest Value After Replacing With Sum of Prime Factors is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2507. Smallest Value After Replacing With Sum of Prime Factors?
- The Python solution on this page runs in O(\sqrt{n}).
- What is the space complexity of LeetCode 2507. Smallest Value After Replacing With Sum of Prime Factors?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2507. Smallest Value After Replacing With Sum of Prime Factors cover?
- LeetCode 2507. Smallest Value After Replacing With Sum of Prime Factors is tagged Math, Number Theory and Simulation on LeetCode.