Difficulty: Easy | Acceptance: 88.30% | Paid: No Topics: Math, Number Theory
Given a positive integer n, return the smallest positive multiple of n that is also even.
- Examples
- Constraints
- Brute Force
- Mathematical (LCM)
- Direct Formula
- Bit Manipulation
Examples
Example 1
Input: n = 5
Output: 10
Explanation: The smallest positive multiple of 5 that is also even is 10.
Example 2
Input: n = 6
Output: 6
Explanation: The smallest positive multiple of 6 that is also even is 6 itself.
Constraints
1 <= n <= 150
Brute Force
Intuition Start from n and keep adding n until we find an even number.
Steps
- If n is even, return n
- Otherwise, keep adding n to the result until it becomes even
python
class Solution:
def smallestEvenMultiple(self, n: int) -> int:
result = n
while result % 2 != 0:
result += n
return result
Complexity
- Time: O(1) - at most one iteration needed
- Space: O(1)
- Notes: Simple but not the most efficient
Mathematical (LCM)
Intuition The smallest even multiple of n is the LCM of n and 2.
Steps
- Calculate LCM(n, 2) = (n * 2) / GCD(n, 2)
- If n is even, GCD(n, 2) = 2, so LCM = n
- If n is odd, GCD(n, 2) = 1, so LCM = 2n
python
import math
class Solution:
def smallestEvenMultiple(self, n: int) -> int:
return (n * 2) // math.gcd(n, 2)
Complexity
- Time: O(log(min(n, 2))) = O(1) for GCD calculation
- Space: O(1)
- Notes: Uses the mathematical relationship between LCM and GCD
Direct Formula
Intuition If n is even, n itself is the answer. If n is odd, we need to multiply by 2.
Steps
- Check if n is even using modulo operation
- If even, return n
- If odd, return 2 * n
python
class Solution:
def smallestEvenMultiple(self, n: int) -> int:
return n if n % 2 == 0 else 2 * n
Complexity
- Time: O(1)
- Space: O(1)
- Notes: Most efficient and readable approach
Bit Manipulation
Intuition Check the least significant bit to determine if n is even or odd.
Steps
- Use bitwise AND with 1 to check if n is odd
- If n & 1 is 0, n is even, return n
- If n & 1 is 1, n is odd, return n << 1 (n * 2)
python
class Solution:
def smallestEvenMultiple(self, n: int) -> int:
return n if (n & 1) == 0 else n << 1
Complexity
- Time: O(1)
- Space: O(1)
- Notes: Uses bitwise operations which can be slightly faster than modulo