2413. Smallest Even Multiple
Problem Description
Given a positive integer n, you need to find the smallest positive integer that is a multiple of both 2 and n.
In other words, you're looking for the least common multiple (LCM) of 2 and n. This number must be divisible by both 2 and n, and it should be the smallest such positive integer.
For example:
- If
n = 5, the smallest number that is a multiple of both2and5is10 - If
n = 6, the smallest number that is a multiple of both2and6is6itself (since6is already even)
The solution leverages a simple mathematical observation:
- When
nis even (divisible by2), thennitself is already a multiple of both2andn, so the answer isn - When
nis odd, the smallest multiple of both2andnisn * 2
This is because when n is odd, it has no factor of 2, so we need to multiply it by 2 to make it even while still being a multiple of n.
Intuition
To find the smallest positive integer that is a multiple of both 2 and n, we need to think about what makes a number divisible by both values.
A number that is divisible by both 2 and n must contain all the prime factors of both numbers. Since 2 is a prime number itself, our result must be even (contain at least one factor of 2).
Let's consider two cases:
-
When
nis even: Ifnis already even, it meansnalready contains2as a factor. For example, ifn = 6, thenn = 2 × 3. Sincenalready has the factor2, it's automatically divisible by both2and itself. Therefore,nis the smallest such multiple. -
When
nis odd: Ifnis odd, it doesn't contain2as a factor. For example, ifn = 5, then to create a number divisible by both2and5, we need to include both factors. The smallest way to do this is to multiplynby2, giving us2n. This ensures our number has the factor2(making it even) while maintaining all factors ofn.
This leads us to a simple decision: check if n is even using the modulo operator (n % 2). If the remainder is 0, then n is even and already our answer. Otherwise, we need to multiply n by 2.
Learn more about Math patterns.
Solution Implementation
1class Solution:
2 def smallestEvenMultiple(self, n: int) -> int:
3 """
4 Find the smallest positive integer that is a multiple of both 2 and n.
5
6 Args:
7 n: A positive integer
8
9 Returns:
10 The smallest positive integer that is divisible by both 2 and n
11 """
12 # If n is already even, it's divisible by both 2 and n
13 if n % 2 == 0:
14 return n
15 # If n is odd, the smallest number divisible by both 2 and n is n * 2
16 else:
17 return n * 2
181class Solution {
2 /**
3 * Finds the smallest positive integer that is a multiple of both 2 and n.
4 *
5 * @param n The given positive integer
6 * @return The smallest even multiple of n
7 */
8 public int smallestEvenMultiple(int n) {
9 // If n is already even, it is divisible by both 2 and n
10 if (n % 2 == 0) {
11 return n;
12 }
13 // If n is odd, multiply by 2 to get the smallest even multiple
14 else {
15 return n * 2;
16 }
17 }
18}
191class Solution {
2public:
3 /**
4 * Finds the smallest positive integer that is a multiple of both 2 and n.
5 *
6 * @param n - The input positive integer
7 * @return The smallest even multiple of n
8 *
9 * Logic:
10 * - If n is already even (divisible by 2), then n itself is the smallest even multiple
11 * - If n is odd, then n * 2 is the smallest even multiple
12 */
13 int smallestEvenMultiple(int n) {
14 // Check if n is even
15 if (n % 2 == 0) {
16 // n is already even, so it's the smallest even multiple of itself
17 return n;
18 } else {
19 // n is odd, so multiply by 2 to get the smallest even multiple
20 return n * 2;
21 }
22 }
23};
241/**
2 * Finds the smallest positive integer that is a multiple of both 2 and n
3 * @param n - The input number to find the smallest even multiple of
4 * @returns The smallest positive integer that is divisible by both 2 and n
5 */
6function smallestEvenMultiple(n: number): number {
7 // If n is already even, it's divisible by both 2 and n
8 // If n is odd, multiply by 2 to get the smallest even multiple
9 return n % 2 === 0 ? n : n * 2;
10}
11Solution Approach
The implementation follows directly from our mathematical understanding of the least common multiple (LCM) of 2 and n.
The algorithm is straightforward:
-
Check if
nis even: We use the modulo operatorn % 2to determine ifnis divisible by2.- If
n % 2 == 0, thennis even
- If
-
Return the appropriate result:
- If
nis even, the LCM of2andnis simplynitself - If
nis odd, the LCM of2andnisn * 2
- If
The solution can be implemented in a single line using a conditional expression:
return n if n % 2 == 0 else n * 2
This approach works because:
- For even
n: Sincen = 2kfor some integerk, both2andndividen - For odd
n: Sincegcd(2, n) = 1whennis odd, the LCM formula gives usLCM(2, n) = (2 * n) / gcd(2, n) = 2n / 1 = 2n
The time complexity is O(1) as we only perform a constant number of operations (one modulo check and possibly one multiplication). The space complexity is also O(1) as we don't use any additional data structures.
Ready to land your dream job?
Unlock your dream job with a 5-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's walk through the solution with two examples to illustrate both cases:
Example 1: n = 5 (odd number)
-
First, we check if
nis even by calculatingn % 2:5 % 2 = 1(remainder is 1, so 5 is odd)
-
Since
nis odd, we need to multiply it by 2:- Result =
5 * 2 = 10
- Result =
-
Verification:
- Is 10 divisible by 2? Yes:
10 ÷ 2 = 5 - Is 10 divisible by 5? Yes:
10 ÷ 5 = 2 - Is 10 the smallest such number? Yes, because:
- 5 is not divisible by 2
- Any smaller multiple of 5 (which is just 5 itself) isn't even
- Is 10 divisible by 2? Yes:
Example 2: n = 6 (even number)
-
First, we check if
nis even by calculatingn % 2:6 % 2 = 0(remainder is 0, so 6 is even)
-
Since
nis even, it already contains the factor 2:- Result =
6
- Result =
-
Verification:
- Is 6 divisible by 2? Yes:
6 ÷ 2 = 3 - Is 6 divisible by 6? Yes:
6 ÷ 6 = 1 - Is 6 the smallest such number? Yes, because any positive multiple of 6 would be at least 6
- Is 6 divisible by 2? Yes:
The algorithm correctly identifies that odd numbers need to be doubled to become multiples of 2, while even numbers are already multiples of both 2 and themselves.
Time and Space Complexity
Time Complexity: O(1)
The function performs a constant number of operations regardless of the input size:
- One modulo operation (
n % 2) - One comparison (
== 0) - One conditional return with either direct return of
nor one multiplication (n * 2)
All these operations take constant time, resulting in O(1) time complexity.
Space Complexity: O(1)
The function uses only a constant amount of extra space:
- No additional data structures are created
- Only the input parameter
nand the return value are stored - The space used does not grow with the input size
Therefore, the space complexity is O(1).
Learn more about how to find time and space complexity quickly.
Common Pitfalls
1. Overthinking the Mathematical Formula
Many developers might try to implement the full LCM formula using GCD (Greatest Common Divisor):
def gcd(a, b):
while b:
a, b = b, a % b
return a
def smallestEvenMultiple(n):
return (2 * n) // gcd(2, n) # Unnecessarily complex
Why it's a pitfall: While mathematically correct, this approach is overly complex for this specific problem where one number is always 2. The GCD calculation adds unnecessary overhead.
Solution: Recognize that when dealing with 2 specifically:
- GCD(2, even_number) = 2
- GCD(2, odd_number) = 1
This simplifies to the straightforward even/odd check.
2. Using Bitwise Operations Without Clear Understanding
Some might attempt to optimize using bitwise operations:
def smallestEvenMultiple(n):
return n << (n & 1) # Clever but unclear
Why it's a pitfall: While this works (it left-shifts n by 1 if n is odd, 0 if even), it sacrifices readability for marginal performance gain. The bitwise approach can confuse team members and make debugging harder.
Solution: Stick with the clear, readable approach using modulo unless performance profiling specifically shows this function as a bottleneck.
3. Not Handling Edge Cases in Interview Settings
In an interview, candidates might forget to clarify constraints:
def smallestEvenMultiple(n):
# What if n is 0 or negative?
return n if n % 2 == 0 else n * 2
Why it's a pitfall: The problem states n is positive, but in real-world scenarios or extended versions of the problem, you might need to handle:
- n = 0 (mathematically undefined LCM)
- Negative numbers
- Very large numbers causing overflow
Solution: Add input validation if the problem constraints aren't guaranteed:
def smallestEvenMultiple(n):
if n <= 0:
raise ValueError("n must be a positive integer")
return n if n % 2 == 0 else n * 2
4. Misunderstanding the Problem Statement
Some might interpret "smallest multiple" as finding factors instead:
def smallestEvenMultiple(n):
# Wrong: trying to find smallest factor
for i in range(2, n + 1):
if i % 2 == 0 and n % i == 0:
return i
return n * 2
Why it's a pitfall: This finds the smallest even divisor of n, not the LCM of 2 and n.
Solution: Carefully read the problem - we need a number divisible by BOTH 2 and n, not a number that divides n.
A heap is a ...?
Recommended Readings
Math for Technical Interviews How much math do I need to know for technical interviews The short answer is about high school level math Computer science is often associated with math and some universities even place their computer science department under the math faculty However the reality is that you
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion If you prefer videos here's a video that explains recursion in a fun and easy way Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https assets algo monster recursion jpg You first call Ben and ask him
Want a Structured Path to Master System Design Too? Don’t Miss This!