0

So I am currently working on that function

const countSixes = n => {
  if (n === 0) return 0;
  else if (n === 1) return 1;
  else n = (countSixes(n-1) + countSixes(n-2)) / 2;

  return n;
}

And so my question is how to convert the final floating-point value into a string?

Every time after calling the function and trying to convert the float number it returns NaN


What I've Tried

  1. "" + value
  2. String(value)
  3. value.toString()
  4. value.toFixed(2)

Hope to get the answer

Thank you!

4
  • what value do you expect? please add an example. Commented Jan 29, 2019 at 18:44
  • I copied your function exactly as posted, ran it in the chrome console and added a toString() at the end of the call and got a string output, what value are you calling this function with? Commented Jan 29, 2019 at 18:47
  • Each of those should work , can you give a larger example and explain what you want and what happens instead? Commented Jan 29, 2019 at 18:48
  • Issue is you are using it in recursive manner so you probably were using inside the function call so you were subtracting strings? Hard to tell since you did not show how you were converting it to a string. Commented Jan 29, 2019 at 18:54

3 Answers 3

1

The first option works for me

<script>
const countSixes = n => {
  if (n === 0) return 0;
  else if (n === 1) return 1;
  else n = (countSixes(n-1) + countSixes(n-2)) / 2;

  return n;
}

alert(countSixes(12) + "")
</script>

Sign up to request clarification or add additional context in comments.

Comments

1

The problem is really interesting. Its return NaN because when you return n as String, as the function is called recursively so it cannot perform arithmetic operations in next level.
It will never end for certain numbers like 55

function countSixes(n,firstTime=true){
        if (n === 0) return 0;
        else if (n === 1) return 1;
        else n = (countSixes(n-1,false) + countSixes(n-2,false)) / 2;
        if(firstTime) return n.toFixed(10);    // return string
        else return parseFloat(n.toFixed(10));      // return float
    }

2 Comments

I would define countSixes() as entry and countSixesHelper() as recursive part.
I would also do that but i posted this in hurry
0

You could convert the final value to a string with the wanted decimals.

const countSixes = n => {
    if (n === 0) return 0;
    if (n === 1) return 1;
    return (countSixes(n - 1) + countSixes(n - 2)) / 2;
}

console.log(countSixes(30).toFixed(15));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.