|
| 1 | +/** |
| 2 | + * Write a program to find the nth super ugly number. |
| 3 | + * <p> |
| 4 | + * Super ugly numbers are positive numbers whose all prime factors are in the given prime list primes of size k. For |
| 5 | + * example, [1, 2, 4, 7, 8, 13, 14, 16, 19, 26, 28, 32] is the sequence of the first 12 super ugly numbers given |
| 6 | + * primes = [2, 7, 13, 19] of size 4. |
| 7 | + * <p> |
| 8 | + * Note: |
| 9 | + * (1) 1 is a super ugly number for any given primes. |
| 10 | + * (2) The given numbers in primes are in ascending order. |
| 11 | + * (3) 0 < k ≤ 100, 0 < n ≤ 106, 0 < primes[i] < 1000. |
| 12 | + * (4) The nth super ugly number is guaranteed to fit in a 32-bit signed integer. |
| 13 | + * <p> |
| 14 | + * Credits: |
| 15 | + * Special thanks to @dietpepsi for adding this problem and creating all test cases. |
| 16 | + * <p> |
| 17 | + * Created by drfish on 16/06/2017. |
| 18 | + */ |
| 19 | +public class _313SuperUglyNumber { |
| 20 | + public int nthSuperUglyNumber(int n, int[] primes) { |
| 21 | + int[] indexes = new int[primes.length]; |
| 22 | + int[] superUgly = new int[n]; |
| 23 | + |
| 24 | + superUgly[0] = 1; |
| 25 | + for (int i = 1; i < n; i++) { |
| 26 | + superUgly[i] = Integer.MAX_VALUE; |
| 27 | + for (int j = 0; j < primes.length; j++) { |
| 28 | + superUgly[i] = Math.min(superUgly[i], primes[j] * superUgly[indexes[j]]); |
| 29 | + } |
| 30 | + for (int j = 0; j < primes.length; j++) { |
| 31 | + while (primes[j] * superUgly[indexes[j]] <= superUgly[i]) { |
| 32 | + indexes[j]++; |
| 33 | + } |
| 34 | + } |
| 35 | + } |
| 36 | + return superUgly[n - 1]; |
| 37 | + } |
| 38 | + |
| 39 | + public static void main(String[] args) { |
| 40 | + _313SuperUglyNumber solution = new _313SuperUglyNumber(); |
| 41 | + assert 32 == solution.nthSuperUglyNumber(12, new int[]{2, 7, 13, 19}); |
| 42 | + } |
| 43 | +} |
0 commit comments