Smallest Even Multiple

Easy
571.

Smallest Even Multiple

Smallest Even Multiple is an easy coding problem on math and number theory, asked in Amazon and TCS interviews.

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
Write your solution here. Running it against the tests needs a free account — what you type comes with you.Sign in to run
/**
 * @param {number} n
 * @return {number}
 */
var smallestEvenMultiple = function(n) {
    // Write your code here
    
};

Sign in to run your own test cases

Sign in

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

  1. Hint 1

    This is the least common multiple of 2 and n.

  2. Hint 2

    If n is already even it is its own answer.

  3. Hint 3

    Otherwise the answer is 2n, since 2 and an odd n share 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

  1. If n is even, return n.
  2. 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 * n unconditionally overshoots for even inputs.
  • n = 1 answers 2, which the odd branch handles.

Reference solution

Python

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

Java

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.

All 337 math problems · the whole catalogue