Count the Number of Ideal Arrays LeetCode solution in Python
1from math import sqrt234class Solution:5def primesUpTo(self, n):6primes = set(range(2, n + 1))7for i in range(2, n):8if i in primes:9it = i * 210while it <= n:11if it in primes:12primes.remove(it)13it += i1415return primes1617def getPrimeFactors(self, n, primes):18ret = {}19sq = int(math.sqrt(n))2021for p in primes:22if n in primes:23ret[n] = 124break2526while n % p == 0:27ret[p] = ret.get(p, 0) + 128n //= p2930if n <= 1:31break3233return ret3435def idealArrays(self, n: int, maxValue: int) -> int:36mod = 10**9 + 737ret = 038primes = self.primesUpTo(maxValue)3940for num in range(1, maxValue + 1):41# find number of arrays that can end with num42# for each prime factor, we can add it at any index i that we want43pf = self.getPrimeFactors(num, primes)44cur = 145for d in pf:46ct = pf[d]47v = n48# there are (n + 1) choose k ways to add k prime factors49for add in range(1, ct):50v *= n + add51v //= add + 15253cur = (cur * v) % mod5455ret = (ret + cur) % mod5657return ret