Smallest Even Multiple — Solution in Python, Java & C++
Smallest Even Multiple solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem.
Smallest Even Multiple is an easy coding problem on math and number theory, asked in Amazon and TCS interviews.
- Difficulty: Easy
- Topics: Math, Number Theory
- Asked at: Amazon, TCS
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
Given a positive integer n, return the smallest positive integer that is a multiple of both 2 and n.
Example 1
Input: n = 5
Output: 10
Explanation: 10 is the smallest multiple of both 2 and 5.
Example 2
Input: n = 6
Output: 6
Explanation: 6 is already even.
Example 3
Input: n = 1
Output: 2
Constraints
1 <= n <= 150
Hints for Smallest Even Multiple
Hint 1
This is the least common multiple of 2 and
n.Hint 2
If
nis already even it is its own answer.Hint 3
Otherwise the answer is
2n, since 2 and an oddnshare no factor.
How to solve Smallest Even Multiple
lcm(2, n) = 2n / gcd(2, n), and gcd(2, n) is 2 when n is even and 1 when it is odd — which collapses to a single parity test.
Approach
- If
nis even, returnn. - Otherwise return
2 * n.
Why it works
An even n is already a multiple of 2, so nothing smaller works. An odd n shares no factor with 2, so the least common multiple is their product.
Complexity
- Time —
O(1) - Space —
O(1)
Pitfalls
- Returning
2 * nunconditionally overshoots for even inputs. n = 1answers 2, which the odd branch handles.
Reference solution
Python
def smallestEvenMultiple(n: int) -> int:
return n if n % 2 == 0 else n * 2Java
public static int smallestEvenMultiple(int n) {
return n % 2 == 0 ? n : n * 2;
}C++
int smallestEvenMultiple(int n) {
return n % 2 == 0 ? n : n * 2;
}JavaScript
var smallestEvenMultiple = function(n) {
return n % 2 === 0 ? n : n * 2;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.