All problems

Problem 852

Super Ugly Number

Medium · 20 pts · Math, Dynamic Programming, Heap

Problem

A super ugly number is a positive integer whose prime factors all belong to a given list of primes. The number 1 is the first super ugly number. Print the N-th super ugly number. Generate them in increasing order like the classic ugly-number algorithm: keep one pointer per prime into the list built so far, take the smallest candidate prime × list[pointer] as the next number, and advance every pointer that produced it. The tests are chosen so that the answer, and every candidate prime × list[pointer] computed along the way, fits in a signed 64-bit integer. That is more than a 32-bit int can hold, so use long long in C++ or long in Java (Python needs nothing special).

Input

The first line contains N and K. The second line contains the K distinct primes in increasing order.

Output

Print the N-th super ugly number.

Constraints

1 <= N <= 10000; 1 <= K <= 50; 2 <= primes <= 1000; the answer and every candidate fit in a signed 64-bit integer

Example input

12 4
2 7 13 19

Example output

32

Explanation

With primes 2 7 13 19, the super ugly numbers start 1, 2, 4, 7, 8, 13, 14, 16, 19, 26, 28, 32. The 12th one is 32.

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

Previous: Number of Steps to Reduce a Number to Zero Next: Smallest Integer Divisible by K