19 December 2023 — 2 min read
Given n find the kth factor
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
Time complexity → O(n)
Space complexity → O(n)
// 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];
};
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;
};