I recently encountered this problem:
There is a (increasingly) sorted array formed by multiplying any two or more consecutive natural numbers.
2, 6, 12, 20, 24, 30, 42, 56, 60, 72 ...Ex. 2 is formed by two consecutive natural numbers 1 and 2: 2 = 1×2. And 6 = 2×3 OR 1×2×3, 20 = 4×5.
If n is given as a parameter, find the nth number from the above array and return.
Limitation
- 1 ≤ n ≤ 1000000
- n is given only when the answer is smaller than 1012
So here I was able to find O(n2) solution, but I want to know if there is a better solution.
My O(n2) JS solution:
function solution(n) {
// Find all possible product subsets of [1, ..., n] = [1x2, 2x3, 4x5, ..., 1x2x...xn]
// return Nth index of this product subset array
// 1 ~ n+1 array
const nums = Array.from({ length: n+1 }, (_, i) => i + 1);
const set = new Set();
// Find all possible product subsets
for (let i = 0; i < nums.length; i++) {
let accu = 1;
for (let j = i; j < nums.length; j++) {
accu *= nums[j];
if (i !== j) set.add(accu);
}
}
// Sort and return n-1 index value
return Array.from(set).sort((a,b) => a - b)[n-1];
}
Thanks for the help :)