Basic Algorithm Scripting - Factorialize a Number

Tell us what’s happening:

Can anyone tell me why my code isn’t working?

Your code so far

function factorialize(num) {
  if (num < 0) {
    return "Not applicable for this number";
  }
  else if (num = 0) {
    return 1;
  }
  else if (num > 0) {
    const seqNumbers = factorialize(num - 1);
    let num = num*seqNumbers;
    return num;
  }
}
console.log(factorialize(5));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36

Challenge Information:

Basic Algorithm Scripting - Factorialize a Number

What test cases are failing? Have you tried seeing what if-else case you always trigger?

You always return 1

function factorialize(num) {
  if (num < 0) {
    return "Not applicable for this number";
  } else if (num = 0) {
    return 1;
  } else if (num > 0) { // no need for an if here
    const seqNumbers = factorialize(num - 1);
    let num = num * seqNumbers; // why shadow the outer variable `num`?
    return num;
  }
}

Do these affect the result anyway ? Logically I don’t think so.

Two of my three comments certainly effect the result.

I removed the if and introduced a new variable. But still returning NaN. Btw ,you have only two comments.

function factorialize(num) {
  if (num < 0) {
    return "Not applicable for this number";
  }
  else if (num = 0) {
    return 1;
  }
  else {
    const seqNumbers = factorialize(num - 1);
    console.log(seqNumbers);
    let multNum = multNum*seqNumbers;
    return multNum;

  }
}

console.log(factorialize(5));

BTW I also said this above!


function factorialize(num) {
  if (num < 0) {
    return "Not applicable for this number";
  } else if (num = 0) {
    return 1;
  } else {
    const seqNumbers = factorialize(num - 1);
    console.log(seqNumbers); // this not do what you want - why?
    let multNum = multNum*seqNumbers;
    return multNum;
  }
}

console.log(factorialize(5));

I have tried it. I have thought this way. If I could figure out that WHY then I wouldn’t have to post it here.

In my logic it should be working

What does this do? Its breaking your code.

It is the base line. We know we have to use a baseline when using recursive function.

Its supposed to be a base case, but the condition isn’t correct.

Thanks a ton. I figured it out. Looks like it gets easy to identify syntax errors after a goodnights sleep. :smiling_face_with_tear:

2 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.