kth factor
19 December 2023 • 2 min read
Description
Given n find the kth factor
High-Level Approach
- Generate n factors, store them in an array, then index the kth factor
Low-Level Approach
-
Create the function blueprint that takes in the required parameters and then returns the default results in the required type
-
Add the logic of getting all factors of n number and print them to test if the factors are correct
-
Since we now know how to check factors of n, but we haven't solved the problem which is getting the kth factor of n, we need to store the factors so that we can return the kth factor from the array as results
Complexity
-
Time complexity → O(n)
-
Space complexity → O(n)
Code
// Create the blueprint
function kthFactor(n: number, k: number): number {
let res = -1;
return res;
};
// Add the logic of getting a factor
function kthFactor(n: number, k: number): number {
let res = -1;
let possibleFactor = 1;
while (possibleFactor <= n) {
if (n % possibleFactor === 0) {
console.log(possibleFactor);
}
possibleFactor++;
}
return res;
};
// We now know how to check factors of n, but we haven't solved the problem which is getting the kth factor of n, so we need a count
function kthFactor(n: number, k: number): number {
let possibleFactor = 1;
let factors = [];
while (possibleFactor <= n) {
if (n % possibleFactor === 0) {
factors.push(possibleFactor);
}
possibleFactor++;
}
return factors.length < k ? -1 : factors[k - 1];
};
Improvements
- We have solved the problem, but we have unnecessary variables and processing that we can do without, such as stopping when the possibleFactor is the kth and pushing all the factors in an array. So, to be memory efficient, we can store the latest factor since we just want to know one value. We can terminate early when the kth factor has been found to avoid unnecessary iterations
function kthFactor(n: number, k: number): number {
let possibleFactor = 1;
let foundFactors = 0;
while (possibleFactor <= n && foundFactors < k) {
if (n % possibleFactor === 0) {
foundFactors++;
}
possibleFactor++;
}
return foundFactors === k ? (possibleFactor - 1) : -1;
};