1510. Kth Coprime Ticket

A festival hands out numbered tickets 1, 2, 3, ... but the gate with code n only admits tickets whose number shares no common divisor larger than 1 with n (the ticket and n must be coprime). Counting only admitted tickets in increasing order, you want to find the k-th one.

Return the k-th smallest positive integer that is coprime to n, as a 64-bit integer. Factor n into its distinct primes; for any bound x the number of admitted tickets up to x follows from inclusion-exclusion over subsets of those primes (add or subtract floor(x / product)), and it never decreases as x grows, so binary search x. Expected time is about O(sqrt(n) + 2^w log X), where w is the number of distinct primes, with O(2^w) extra space.

Example 1

Input:
n = 12, k = 5
Output:
13
Explanation:

Numbers coprime to 12 are 1, 5, 7, 11, 13, ..., so the fifth is 13.

Example 2

Input:
n = 1, k = 9
Output:
9
Explanation:

Every number is coprime to 1, so the ninth ticket is simply 9.

Example 3

Input:
n = 30, k = 3
Output:
11
Explanation:

Numbers coprime to 30 start 1, 7, 11, so the third is 11.

Constraints

1 ≤ n ≤ 1012

1 ≤ k ≤ 1012

The answer is below 1014.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(sqrt(n) + 2^w log X)
Space
O(2^w)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…