Problem#
Given a positive integer n
, return _the smallest positive integer that is a multiple ofboth _2
and n
.
Examples#
Example 1#
1
2
3
4
5
6
7
Input: n = 5
Output: 10
Explanation: The smallest multiple of both 5 and 2 is 10.
Example 2#
1
2
3
4
5
6
7
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#
Solution#
Method 1 – Simple Math (LCM)#
Intuition#
The smallest number that is a multiple of both n and 2 is their least common multiple (LCM). For any integer n, LCM(n, 2) is n if n is even, or 2n if n is odd.
Approach#
If n is even, return n.
If n is odd, return 2 * n.
Code#
Cpp
Java
Python
1
2
3
4
5
6
class Solution {
public :
int smallestEvenMultiple(int n) {
return n % 2 == 0 ? n : 2 * n;
}
};
1
2
3
4
5
class Solution {
public int smallestEvenMultiple (int n) {
return n % 2 == 0 ? n : 2 * n;
}
}
1
2
3
class Solution :
def smallestEvenMultiple (self, n: int) -> int:
return n if n % 2 == 0 else 2 * n
Complexity#
⏰ Time complexity: O(1)
— Constant time arithmetic.
🧺 Space complexity: O(1)
— No extra space used.