# C++ program to find Nth Non Fibonacci Number

In this problem, we are given an integer value N. Our task is to use a C + + program to find the Nth Non Fibonacci Number.

Fibonacci Series generates subsequent number by adding two previous numbers. The Fibonacci series starts from two numbers − F0 & F1. The initial values of F0 & F1 can be taken 0, 1 or 1, 1 respectively.

Let’s take an example to understand the problem,

Input

N = 5

Output

10

## Solution Approach

A simple solution to the problem is to find the Fibonacci numbers and then print the first n numbers which are not present in the Fibonacci Numbers.

Another solution is using the fibonacci number formula and then keep adding the gap between two fibonacci numbers consecutively. At last, the value of the sum of all gaps would result in the desired output. Here we would be using the sensible idea for cracking.

## Algorithm

• Create three variables which will keep track of the current element, previous element and the previous element.

• While count of non Fibonacci is non negative, use the simple formula of Fibonacci number − Fib(n)=Fib(n-1)+Fib(n-2).

• To get the count of non Fibonacci numbers by using the formula n=n+(curr-prev-1).

• Now to get the nth non Fibonacci number subtract the previous number from n.

## Example

Program to illustrate the working of our solution

#include<iostream>
using namespace std;
int findNthNonFiboNumber(int n){
int lastLastVal = 1, lastVal = 2, currVal = 3;
while (n > 0){
lastLastVal = lastVal;
lastVal = currVal;
currVal = lastLastVal + lastVal;
n = n - (currVal - lastVal - 1);
}
n = n + (currVal - lastVal - 1);
return (lastVal + n);
}
int main(){
int n = 7;
cout<<"Nth non fibonacci number is "<<findNthNonFiboNumber(n);
return 0;
}

## Output

Nth non fibonacci number is 12