|
| 1 | +/** |
| 2 | + * 2338. Count the Number of Ideal Arrays |
| 3 | + * https://leetcode.com/problems/count-the-number-of-ideal-arrays/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given two integers n and maxValue, which are used to describe an ideal array. |
| 7 | + * |
| 8 | + * A 0-indexed integer array arr of length n is considered ideal if the following conditions hold: |
| 9 | + * - Every arr[i] is a value from 1 to maxValue, for 0 <= i < n. |
| 10 | + * - Every arr[i] is divisible by arr[i - 1], for 0 < i < n. |
| 11 | + * |
| 12 | + * Return the number of distinct ideal arrays of length n. Since the answer may be very large, |
| 13 | + * return it modulo 109 + 7. |
| 14 | + */ |
| 15 | + |
| 16 | +/** |
| 17 | + * @param {number} n |
| 18 | + * @param {number} maxValue |
| 19 | + * @return {number} |
| 20 | + */ |
| 21 | +var idealArrays = function(n, maxValue) { |
| 22 | + const MOD = 1e9 + 7; |
| 23 | + const MAX_N = 10010; |
| 24 | + const MAX_P = 15; |
| 25 | + |
| 26 | + const c = Array.from({ length: MAX_N + MAX_P }, () => |
| 27 | + new Array(MAX_P + 1).fill(0) |
| 28 | + ); |
| 29 | + const sieve = new Array(MAX_N).fill(0); |
| 30 | + const ps = Array.from({ length: MAX_N }, () => []); |
| 31 | + |
| 32 | + for (let i = 2; i < MAX_N; i++) { |
| 33 | + if (sieve[i] === 0) { |
| 34 | + for (let j = i; j < MAX_N; j += i) { |
| 35 | + if (sieve[j] === 0) { |
| 36 | + sieve[j] = i; |
| 37 | + } |
| 38 | + } |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + for (let i = 2; i < MAX_N; i++) { |
| 43 | + let x = i; |
| 44 | + while (x > 1) { |
| 45 | + const p = sieve[x]; |
| 46 | + let cnt = 0; |
| 47 | + while (x % p === 0) { |
| 48 | + x = Math.floor(x / p); |
| 49 | + cnt++; |
| 50 | + } |
| 51 | + ps[i].push(cnt); |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + c[0][0] = 1; |
| 56 | + for (let i = 1; i < MAX_N + MAX_P; i++) { |
| 57 | + c[i][0] = 1; |
| 58 | + for (let j = 1; j <= Math.min(i, MAX_P); j++) { |
| 59 | + c[i][j] = (c[i - 1][j] + c[i - 1][j - 1]) % MOD; |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + let ans = 0n; |
| 64 | + for (let x = 1; x <= maxValue; x++) { |
| 65 | + let mul = 1n; |
| 66 | + for (const p of ps[x]) { |
| 67 | + mul = (mul * BigInt(c[n + p - 1][p])) % BigInt(MOD); |
| 68 | + } |
| 69 | + ans = (ans + mul) % BigInt(MOD); |
| 70 | + } |
| 71 | + |
| 72 | + return Number(ans); |
| 73 | +}; |
0 commit comments