javascript
Parameters: startNumber (Number), endNumber (Number)
startNumber: lower range, endNumber: upper range
Returns: Returns an array of Fibonacci numbers within a given range
The 'findFibonacciNumbersRange' function in Javascript generates and returns the Fibonacci numbers within a specified range. It accepts two parameters, representing the start and end of the range.
Hello, fellow programmer! Today, we will go over how to build a function in JavaScript to find a range of Fibonacci numbers. The Fibonacci sequence is a series of numbers where a number is the sum of the two preceding ones, usually starting with 0 and 1. This guide aims to provide clear steps to replicate this mathematical concept into a working function. Let's begin!
Start with declaring variables for the fibonacci sequence, i.e., fib1 and fib2 representing the last two numbers in the sequence, starting from 0 and 1, and fibnext representing the next number in the sequence. Initialize these numbers to 0, 1, and 0 respectively.
let fib1 = 0;
let fib2 = 1;
let fibnext = 0;
Create a loop that continues until the next number in the fibonnaci sequence exceeds the upper limit for your projected range. The upper limit is passed as an argument to our function, findFibonacciNumbersRange(limit)
.
while (fibnext <= limit) {
//Loop will continue till the fibonacci sequence exceeds the limit
}
Inside the loop, first update fibnext
to be the sum of fib1
and fib2
. Make fib1
the value of fib2
, and fib2
the value of fibnext
. This will keep the sequence going.
fibnext = fib1+ fib2;
fib1 = fib2;
fib2 = fibnext;
Introduce a new variable start
representing the lower limit of our desired range. If fibnext
is greater than or equal to start
and less than or equal to limit
, push that number to our fibonacci sequence array.
if(fibnext >= start && fibnext <= limit) {
//push the number to our fibonacci sequence array.
}
Here's the full code that includes all steps:
function findFibonacciNumbersRange(start, limit) {
let fib1 = 0;
let fib2 = 1;
let fibnext = 0;
let fibonacciSequence = [];
while (fibnext <= limit) {
fibnext = fib1 + fib2;
fib1 = fib2;
fib2 = fibnext;
if(fibnext >= start && fibnext <= limit) {
fibonacciSequence.push(fibnext);
}
}
return fibonacciSequence;
}
This function will return all fibonacci numbers that fall in the range specified by start
and limit
.
Generates a sequence of Fibonacci numbers within a given range
Learn moreThe Fibonacci sequence is a series of numbers where a number is found by adding up the two numbers before it. Starting from `0,1`, the sequence goes: `0, 1, 1, 2, 3, 5, 8, 13, 21, 34,` and so forth. The mathematical formula to express this is `F(n) = F(n-1) + F(n-2)` where `F(n)` is term number `n`.
Learn more