H
H
Herberito Galustyan2019-09-12 15:57:14
JavaScript
Herberito Galustyan, 2019-09-12 15:57:14

How to recursively get fibonacci values ​​that are less than a given number?

I need to write a function using recursion without using this array.which will return all fibonacci digit values ​​up to n . n>0;

function fib(number) {
  if (number === 1) {
    return "0,1,1";
  }
  if (number === 2) {
    return "0,1,1,2,";
  } else {
    let fibList = fib(number - 1);
    return (fibList += `${number - 2 + number - 1},`);
  }
}
console.log(fib(45));


my code is not working as i want i dont know how to fix it.

n=7 "0, 1, 1, 2, 3, 5"
n=45 "0, 1, 1, 2, 3, 5, 8, 13, 21, 34"

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2020-10-13
@Herberto

function fib(max) {
  const next = (p1, p2) => p2 <= max ? ',' + p2 + next(p1 + p2, p1) : '';
  return 0 + next(1, 1);
}


fib(0)   // "0"
fib(1)   // "0,1,1"
fib(10)  // "0,1,1,2,3,5,8"
fib(45)  // "0,1,1,2,3,5,8,13,21,34"
fib(100) // "0,1,1,2,3,5,8,13,21,34,55,89"

K
Karpion, 2019-09-12
@Karpion

Why do you have
return "0,1,1";
there is no comma at the end, but in the line
return "0,1,1,2 , ";
is there a comma?
And what is not true at all? What is and what should be?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question