JavaScript Program to Print Nth Non Fibonacci Number
JavaScript program to print the nth non-Fibonacci number. Non-Fibonacci numbers are integers that are not part of the Fibonacci sequence.
Below are the approaches to print the Nth non-Fibonacci number:
Table of Content
- Using a Loop
- Using Recursion
Using a Loop
We are using a while loop to find the nth non-Fibonacci number. we iterate through Fibonacci numbers and we skip them in the count until we reach the nth non-Fibonacci number. We do this by maintaining three variables (prev1, prev2, and cur) to track the current Fibonacci numbers. We decrement N by the difference between the current Fibonacci number and the previous Fibonacci number minus 1 to skip over Fibonacci numbers. After the loop, we adjust N back to get the correct non-Fibonacci number.
Example: To demonstrate printing the nth Non Fibonacci number using a loop.
function findNthNonFibonacci(N) {
let prev1 = 2, prev2 = 1, cur = 3;
while (N > 0) {
let next = prev2 + prev1;
prev2 = prev1;
prev1 = next;
cur = prev2 + prev1;
N = N - (cur - prev1 - 1);
}
N = N + (cur - prev1 - 1);
return prev1 + N;
}
const n = 9;
let nthNonFib = findNthNonFibonacci(n);
console.log(nthNonFib);
Output
15
Using Recursion
This recursive method finds the nth non-Fibonacci number by continuously calculating Fibonacci numbers. It keeps track of the count of non-Fibonacci numbers between consecutive Fibonacci numbers to determine the position of the nth non-Fibonacci number accurately. The function adjusts its search range based on this count and it stops when it finds the nth non-Fibonacci number.
Example: To demonstrate printing the nth Non Fibonacci number using recursion.
function findNthNonFibonacci(N, prev1 = 2, prev2 = 1, cur = 3) {
if (N === 0) {
return prev1 - 1; // Found the nth non-Fibonacci number
}
let next = prev2 + prev1;
prev2 = prev1;
prev1 = next;
cur = prev2 + prev1;
let nonFibCount = cur - prev1 - 1;
if (N <= nonFibCount) {
return prev1 + N;
} else {
return findNthNonFibonacci(N - nonFibCount, prev1, prev2, cur);
}
}
const n = 5;
const nthNonFib = findNthNonFibonacci(n);
console.log(nthNonFib);
Output
10
Contact Us