Smallest Even Multiple solution in Python

Problem Description

So, you think you can find the smallest even multiple of a number? Well, welcome to the club! The problem is simple: given a positive integer n, you need to find the smallest even multiple of n. Sounds easy, right? But wait! What if n is odd? Or what if it’s a prime number? Oh, the drama!

Imagine you’re at a party, and you want to make sure everyone has an even number of snacks. If you have 3 snacks, you can’t just leave it at that; you need to double it to make it 6. But if you have 4 snacks, you’re already good to go! This is the essence of the problem.

Code Solution


class Solution:
    def smallestEvenMultiple(self, n: int) -> int:
        return n * (n % 2 + 1)

Approach

The approach here is as straightforward as it gets. The code checks if n is even or odd. If n is even, it simply returns n. If n is odd, it returns 2n. This is done using the expression n * (n % 2 + 1), which cleverly utilizes the modulus operator to determine if n is even or odd.

Time and Space Complexity

Time Complexity

O(1) – The solution runs in constant time since it involves a simple arithmetic operation.

Space Complexity

O(1) – No additional space is used that scales with input size.

Real-World Example

Let’s say you’re organizing a game night with your friends. You have 5 friends, and you want to make sure everyone gets an even number of game tokens. You can’t just give them 5 tokens; you need to double it to 10! So, the smallest even multiple of 5 is 10. This is exactly what the problem is asking for!

Similar Problems

If you enjoyed this problem, you might also like these:

  • 2-Sum Solution in Python