Smallest Even Multiple
Problem
Given a positive integer n, return the smallest positive integer that is a multiple of both 2 and n. In other words, find the least common multiple of n and 2.
n = 510def smallest_even_multiple(n):
if n % 2 == 0:
return n
return n * 2
function smallestEvenMultiple(n) {
if (n % 2 === 0) {
return n;
}
return n * 2;
}
class Solution {
public int smallestEvenMultiple(int n) {
if (n % 2 == 0) {
return n;
}
return n * 2;
}
}
int smallestEvenMultiple(int n) {
if (n % 2 == 0) {
return n;
}
return n * 2;
}
Explanation
We want the smallest positive number that both 2 and n divide evenly. That is exactly the least common multiple of n and 2, written lcm(n, 2).
There are only two cases to consider, and they hinge on whether n is even or odd.
If n is already even, then n is itself a multiple of 2, and nothing is smaller than n among its own multiples. So the answer is just n.
If n is odd, then n shares no factor of 2 with the number 2. To become divisible by 2 we must multiply by 2, giving 2 × n. This is the smallest even multiple because any smaller multiple of n would have to be n itself, which is odd.
Example: n = 5 is odd, so the answer is 5 × 2 = 10. For n = 6, which is already even, the answer is simply 6.
The whole thing is decided by a single parity check, so it runs in constant time.