Closest Prime Numbers in Range

Given two positive integers left and right, find two primes num1 and num2 with left <= num1 < num2 <= right such that num2 - num1 is as small as possible. Return [num1, num2]. If several pairs share the smallest gap, return the one with the smallest num1. If no such pair exists, return [-1, -1].

30:00

Closest Prime Numbers in Range
medium
Free written solution
Topics
Companies

Given two positive integers left and right, find two primes num1 and num2 with left <= num1 < num2 <= right such that num2 - num1 is as small as possible. Return [num1, num2]. If several pairs share the smallest gap, return the one with the smallest num1. If no such pair exists, return [-1, -1].

Example 1:
Input: {"left":10,"right":19}
Output: [11,13]
Constraints:
  • 1≤left≤right≤1061 \leq left \leq right \leq 10^6

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"left":10,"right":19}

Build a sieve up to 19: every number starts unmarked, and each prime up to sqrt(19) = 4 will cross out its multiples.

sieve 1..19

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

prime

crossed now

prev

current

best pair

primes in [10, 19] and the gaps between them

Scan not started.

best = [-1, -1]
gap = ∞
prev = -1
Variables
VariableValue
left10
right19
DepthFunction Call
Stack empty
0/8