Smallest Even Multiple
EasyPrompt
n, return the smallest positive integer that is a multiple of both 2 and n.
Example 1:
Input: n = 5
Output: 10
Explanation: The smallest multiple of both 5 and 2 is 10.Example 2:
Input: n = 6
Output: 6
Explanation: The smallest multiple of both 6 and 2 is 6. Note that a number is a multiple of itself.
Constraints:
1 <= n <= 150
Approaches
3 approaches with complexity analysis and trade-offs.
This approach simulates a search for the smallest common multiple. We start with the number n and check its multiples one by one (n, 2n, 3n, ...) until we find one that is also a multiple of 2 (i.e., an even number).
Algorithm
-
- Initialize a variable
multipleton.
- Initialize a variable
-
- Start a
whileloop that runs indefinitely.
- Start a
-
- Inside the loop, check if
multipleis even using the modulo operator (multiple % 2 == 0).
- Inside the loop, check if
-
- If it is even, return
multipleas it is the smallest even multiple ofn.
- If it is even, return
-
- If it is odd, update
multipleto the next multiple ofnby addingnto it (multiple += n).
- If it is odd, update
Walkthrough
The algorithm starts by initializing a candidate number, let's call it multiple, to the input n.
It then enters a loop. Inside the loop, it checks if multiple is divisible by 2.
If multiple % 2 == 0, it means we have found the smallest positive integer that is a multiple of both n and 2. The loop terminates, and this value is returned.
If multiple is not divisible by 2, we need to check the next multiple of n. We update multiple by adding n to it (multiple = multiple + n).
The loop continues until an even multiple is found. Since 2 * n is always an even multiple of n, this loop is guaranteed to terminate quickly.
class Solution { public int smallestEvenMultiple(int n) { int multiple = n; while (true) { if (multiple % 2 == 0) { return multiple; } multiple += n; } }}Complexity
Time
O(1). The loop will execute at most twice. If `n` is even, it executes once. If `n` is odd, it executes twice (for `n` and `2n`).
Space
O(1). We only use a single extra variable to store the current multiple.
Trade-offs
Pros
Simple to understand and directly models the process of finding a multiple.
Guaranteed to be correct and terminates quickly for this problem's constraints.
Cons
Involves a loop, which is slightly less direct and efficient than a mathematical or bitwise solution.
For this specific problem, the performance difference is negligible, but as a general approach for finding LCM, it can be slow if the numbers are large.
Solutions
Solution
class Solution {public int smallestEvenMultiple(int n) { return n % 2 == 0 ? n : n * 2; }}Video walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.