{x}
blog image

Smallest Even Multiple

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: 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

2413. Smallest Even Multiple

Problem Description

Given a positive integer n, find the smallest positive integer that is a multiple of both 2 and n.

Solution Explanation

The solution leverages a simple mathematical observation:

  • If n is even: The smallest even multiple of n is n itself, since n is already divisible by 2.
  • If n is odd: The smallest even multiple of n is 2 * n. Multiplying n by 2 guarantees the result is even, and it's the smallest such multiple.

Code Implementation and Complexity Analysis

The solution in various programming languages directly implements this logic using a ternary operator for conciseness.

Time Complexity: O(1) - The solution involves a single modulo operation and a potential multiplication, both of which are constant-time operations. The time taken doesn't depend on the input size n.

Space Complexity: O(1) - The solution uses a constant amount of extra space, regardless of the input value.

Python3

class Solution:
    def smallestEvenMultiple(self, n: int) -> int:
        return n if n % 2 == 0 else n * 2

Java

class Solution {
    public int smallestEvenMultiple(int n) {
        return n % 2 == 0 ? n : n * 2;
    }
}

C++

class Solution {
public:
    int smallestEvenMultiple(int n) {
        return n % 2 == 0 ? n : n * 2;
    }
};

Go

func smallestEvenMultiple(n int) int {
	if n%2 == 0 {
		return n
	}
	return n * 2
}

TypeScript

function smallestEvenMultiple(n: number): number {
    return n % 2 === 0 ? n : n * 2;
}

Rust

impl Solution {
    pub fn smallest_even_multiple(n: i32) -> i32 {
        if n % 2 == 0 {
            return n;
        }
        n * 2
    }
}

C

int smallestEvenMultiple(int n) {
    return n % 2 == 0 ? n : n * 2;
}

All the above code snippets implement the same core logic, differing only in syntax. They all achieve a time complexity of O(1) and a space complexity of O(1).