OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Hackerank "Find the Factor" (in javascript) is failing because of time limit?

  • Thread starter Thread starter Uriah RV
  • Start date Start date
U

Uriah RV

Guest
I had to find all the factors of positive number that evenly divide into a number and then return a p^th element of the list, sorted ascending. If there is no p^th return 0.

I tested almost all the answers i could solve and found online:

Example:

Code:
function pthFactor(n, k) {
let arr = [];
for (let i = 1; i <= n; i++) {
    if (n % i === 0) {
        arr.push(i);
    }
    if (arr.length === k) {
        return arr[arr.length - 1];
    }
}
if (arr.length !== k) {
    return 1;
}
};

or

Code:
var kthFactor = function(n, k) {
let factors = [1]
for(let i=2;i<=Math.floor(n/2);i++){
    if(n%i == 0) factors.push(i)
}
factors.push(n)

return factors.length < k?-1:factors[k-1]
};

buts its failing 10 sec time limit.

What i am doing wrong ?

By the way i also tried Math.sqrt etc in order not to loop n times. Didn't work as well. Do i need to know more than for loop ? Like dynamic programming etc to solve this ?

<p>I had to find all the factors of positive number that evenly divide into a number and then return a <code>p^th</code> element of the list, sorted ascending.
If there is no <code>p^th return 0.</code></p>
<p>I tested almost all the answers i could solve and found online:</p>
<p>Example:</p>
<pre><code>function pthFactor(n, k) {
let arr = [];
for (let i = 1; i <= n; i++) {
if (n % i === 0) {
arr.push(i);
}
if (arr.length === k) {
return arr[arr.length - 1];
}
}
if (arr.length !== k) {
return 1;
}
};
</code></pre>
<p>or</p>
<pre><code>var kthFactor = function(n, k) {
let factors = [1]
for(let i=2;i<=Math.floor(n/2);i++){
if(n%i == 0) factors.push(i)
}
factors.push(n)

return factors.length < k?-1:factors[k-1]
};
</code></pre>
<p>buts its failing 10 sec time limit.</p>
<p>What i am doing wrong ?</p>
<p>By the way i also tried <code>Math.sqrt</code> etc in order not to loop <code>n</code> times. Didn't work as well.
Do i need to know more than for loop ? Like dynamic programming etc to solve this ?</p>
 

Latest posts

Top