All problems

Problem 888

Ugly Number III

Medium · 20 pts · Math, Binary Search, Number Theory

Problem

In this problem an ugly number is a positive integer divisible by A, by B or by C. Print the N-th ugly number. By inclusion-exclusion, the count of ugly numbers up to X is X/A + X/B + X/C - X/lcm(A,B) - X/lcm(A,C) - X/lcm(B,C) + X/lcm(A,B,C) (integer divisions). That count only grows with X, so binary search for the smallest X whose count reaches N.

Input

A single line with N, A, B and C.

Output

Print the N-th ugly number.

Constraints

1 <= N, A, B, C <= 10^9; the answer is at most 2 × 10^9

Example input

3 2 3 5

Example output

4

Explanation

With A = 2, B = 3 and C = 5, the ugly numbers start 2, 3, 4, 5, 6, 8, 9, 10. The third one is 4.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Heaters Next: Design Linked List