Given a positive integer n, the task is to print the nth non-Fibonacci number. The Fibonacci numbers are defined as:
Fib(0) = 0
Fib(1) = 1
for n >1, Fib(n) = Fib(n-1) + Fib(n-2)
First few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 141, ……..
Examples:
Input : n = 2
Output : 6Input : n = 5
Output : 10
Below is the implementation of the above idea.
C++
// C++ program to find n'th Fibonacci number
#include <bits/stdc++.h>
using namespace std;
// Returns n'th Non-Fibonacci number
int nonFibonacci(int n)
{
// curr is to keep track of current fibonacci
// number, prev is previous, prevPrev is
// previous of previous.
int prevPrev = 1, prev = 2, curr = 3;
// While count of non-fibonacci numbers
// doesn't become negative or zero
while (n > 0) {
// Simple Fibonacci number logic
prevPrev = prev;
prev = curr;
curr = prevPrev + prev;
// (curr - prev - 1) is count of
// non-Fibonacci numbers between curr
// and prev.
n = n - (curr - prev - 1);
}
// n might be negative now. Make sure it
// becomes positive by removing last added
// gap.
n = n + (curr - prev - 1);
// n must be now positive and less than or equal
// to gap between current and previous, i.e.,
// (curr - prev - 1);
// Now add the positive n to previous Fibonacci
// number to find the n'th non-fibonacci.
return prev + n;
}
// Driver code
int main()
{
cout << nonFibonacci(5);
return 0;
}
C
// C program to find n'th Fibonacci number
#include<stdio.h>
// Returns n'th Non-Fibonacci number
int nonFibonacci(int n)
{
// curr is to keep track of current fibonacci
// number, prev is previous, prevPrev is
// previous of previous.
int prevPrev=1, prev=2, curr=3;
// While count of non-fibonacci numbers
// doesn't become negative or zero
while (n > 0)
{
// Simple Fibonacci number logic
prevPrev = prev;
prev = curr;
curr = prevPrev + prev;
// (curr - prev - 1) is count of
// non-Fibonacci numbers between curr
// and prev.
n = n - (curr - prev - 1);
}
// n might be negative now. Make sure it
// becomes positive by removing last added
// gap.
n = n + (curr - prev - 1);
// n must be now positive and less than or equal
// to gap between current and previous, i.e.,
// (curr - prev - 1);
// Now add the positive n to previous Fibonacci
// number to find the n'th non-fibonacci.
return prev + n;
}
// Driver code
int main()
{
printf("%d",nonFibonacci(5));
return 0;
}
// This code is contributed by allwink45.
Java
// Java program to find
// n'th Fibonacci number
import java.io.*;
class GFG {
// Returns n'th Non-
// Fibonacci number
static int nonFibonacci(int n)
{
// curr is to keep track of
// current fibonacci number,
// prev is previous, prevPrev
// is previous of previous.
int prevPrev = 1, prev = 2, curr = 3;
// While count of non-fibonacci
// numbers doesn't become
// negative or zero
while (n > 0) {
// Simple Fibonacci number logic
prevPrev = prev;
prev = curr;
curr = prevPrev + prev;
// (curr - prev - 1) is count
// of non-Fibonacci numbers
// between curr and prev.
n = n - (curr - prev - 1);
}
// n might be negative now. Make
// sure it becomes positive by
// removing last added gap.
n = n + (curr - prev - 1);
// n must be now positive and less
// than or equal to gap between
// current and previous, i.e.,
// (curr - prev - 1);
// Now add the positive n to
// previous Fibonacci number
// to find the n'th non-fibonacci.
return prev + n;
}
// Driver Code
public static void main(String args[])
{
System.out.println(nonFibonacci(5));
}
}
// This code is contributed by aj_36
Python
# Python program to find n'th
# Fibonacci number
# Returns n'th Non-Fibonacci
# number
def nonFibonacci(n):
# curr is to keep track of
# current fibonacci number,
# prev is previous, prevPrev
# is previous of previous.
prevPrev = 1
prev = 2
curr = 3
# While count of non-fibonacci
# numbers doesn't become
# negative or zero
while n > 0:
prevPrev = prev
prev = curr
curr = prevPrev + prev
# (curr - prev - 1) is
# count of non-Fibonacci
# numbers between curr
# and prev.
n = n - (curr - prev - 1)
# n might be negative now.
# Make sure it becomes positive
# by removing last added gap.
n = n + (curr - prev - 1)
# n must be now positive and
# less than or equal to gap
# between current and previous,
# i.e., (curr - prev - 1)
# Now add the positive n to
# previous Fibonacci number to
# find the n'th non-fibonacci.
return prev + n
# Driver code
print(nonFibonacci(5))
# This code is contributed by anuj_67.
C#
// C# program to find
// n'th Fibonacci number
using System;
class GFG
{
// Returns n'th Non-
// Fibonacci number
static int nonFibonacci (int n)
{
// curr is to keep track of
// current fibonacci number,
// prev is previous, prevPrev
// is previous of previous.
int prevPrev = 1, prev = 2, curr = 3;
// While count of non-fibonacci
// numbers doesn't become
// negative or zero
while (n > 0)
{
// Simple Fibonacci number logic
prevPrev = prev;
prev = curr;
curr = prevPrev + prev;
// (curr - prev - 1) is count
// of non-Fibonacci numbers
// between curr and prev.
n = n - (curr - prev - 1);
}
// n might be negative now. Make
// sure it becomes positive by
// removing last added gap.
n = n + (curr - prev - 1);
// n must be now positive and less
// than or equal to gap between
// current and previous, i.e.,
// (curr - prev - 1);
// Now add the positive n to
// previous Fibonacci number
// to find the n'th non-fibonacci.
return prev + n;
}
// Driver Code
public static void Main ()
{
Console.WriteLine (nonFibonacci(5));
}
}
//This code is contributed by aj_36
JavaScript
<script>
// Javascript program to find n'th Fibonacci number
// Returns n'th Non-Fibonacci number
function nonFibonacci(n)
{
// curr is to keep track of current fibonacci
// number, prev is previous, prevPrev is
// previous of previous.
let prevPrev=1, prev=2, curr=3;
// While count of non-fibonacci numbers
// doesn't become negative or zero
while (n > 0)
{
// Simple Fibonacci number logic
prevPrev = prev;
prev = curr;
curr = prevPrev + prev;
// (curr - prev - 1) is count of
// non-Fibonacci numbers between curr
// and prev.
n = n - (curr - prev - 1);
}
// n might be negative now. Make sure it
// becomes positive by removing last added
// gap.
n = n + (curr - prev - 1);
// n must be now positive and less than or equal
// to gap between current and previous, i.e.,
// (curr - prev - 1);
// Now add the positive n to previous Fibonacci
// number to find the n'th non-fibonacci.
return prev + n;
}
// Driver code
document.write(nonFibonacci(5));
// This code is contributed by Mayank Tyagi
</script>
PHP
<?php
// PHP program to find
// n'th Fibonacci number
// Returns n'th Non-
// Fibonacci number
function nonFibonacci($n)
{
// curr is to keep track of
// current fibonacci number,
// prev is previous, prevPrev
// is previous of previous.
$prevPrev = 1;
$prev = 2;
$curr = 3;
// While count of non-fibonacci
// numbers doesn't become
// negative or zero
while ($n > 0)
{
// Simple Fibonacci
// number logic
$prevPrev = $prev;
$prev = $curr;
$curr = $prevPrev + $prev;
// (curr - prev - 1) is count
// of non-Fibonacci numbers
// between curr and prev.
$n = $n - ($curr - $prev - 1);
}
// n might be negative now. Make
// sure it becomes positive by
// removing last added gap.
$n = $n + ($curr - $prev - 1);
// n must be now positive and
// less than or equal to gap
// between current and previous,
// i.e., (curr - prev - 1);
// Now add the positive n to
// previous Fibonacci number
// to find the n'th non-fibonacci.
return $prev + $n;
}
// Driver code
echo nonFibonacci(5);
// This code is contributed by m_kit
?>
Output :
10
Time Complexity : O(n) , Auxiliary Space : O(1)
Now geeks you must be wondering what if we were supposed to print Non-Fibonacci Series in a range, then the code is as follows:
C++
#include <iostream>
using namespace std;
int main()
{
int i = 0, j = 1, k, m, no, b[10];
// Range is 10
no = 10;
b[1] = 0;
b[2] = 1;
// Check if range is less equals to 1
if (no <= 1) {
cout << "You have enter a wrong range";
}
// check if range is greater than 1
// and less equals to 5
else if (no <= 5 && no > 1) {
cout << "\nThere is not any Non-Fibonacci series "
"that lies between 1 to "
<< no << " term of Fibonacci Series.";
}
// If range is greater than 5
else {
// Loop to calculate fibonacci series till
// range
for (m = 2; m < no; m++) {
k = i + j;
i = j;
j = k;
// Store fibonacci series into b[]
// array
b[m] = k;
}
i = 5;
cout << "\nThe Non-Fibonacci series that lies "
"between 1 to "
<< no << " term of Fibonacci Series is: \n";
// Loop to calculate Non-Fibonacci
// series
for (int ans = 4; ans < b[no - 1]; ans++) {
if (ans != b[i])
// Print Non-Fibonacci Series
cout << ans << " ";
else
i++;
}
}
return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i = 0, j = 1, k, m, no, b[10];
// Range is 10
no = 10;
b[1] = 0;
b[2] = 1;
// Check if range is less equals to 1
if (no <= 1) {
printf("You have enter a wrong range");
}
// check if range is greater than 1 and less equals to 5
else if (no <= 5 && no > 1) {
printf("\nThere is not any Non-Fibonacci series "
"that lies between 1 to %d term of "
"Fibonacci Series.",
no);
}
// If range is greater than 5
else {
// Loop to calculate fibonacci series till range
for (m = 2; m < no; m++) {
k = i + j;
i = j;
j = k;
// Store fibonacci series into b[] array
b[m] = k;
}
i = 5;
printf(
"\nThe Non-Fibonacci series that lies between "
"1 to %d term of Fibonacci Series is: \n",
no);
// Loop to calculate Non-Fibonacci series
for (int ans = 4; ans < b[no - 1]; ans++) {
if (ans != b[i])
// Print Non-Fibonacci Series
printf("%d ", ans);
else
i++;
}
}
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
int[] holes = {21, 3, 6};
int i = 0, j = 1, k, m, no;
int[] b = new int[10];
// Range is 10
no = 10;
b[1] = 0;
b[2] = 1;
// Check if range is less equals to 1
if (no <= 1) {
System.out.print("You have enter a wrong range");
}
// check if range is greater than 1
// and less equals to 5
else if (no <= 5 && no > 1) {
System.out.print("\n" + "There is not any Non-Fibonacci series that lies between 1 to" + no +
" term of Fibonacci Series.");
}
// If range is greater than 5
else {
// Loop to calculate fibonacci series till
// range
for (m = 2; m < no; m++) {
k = i + j;
i = j;
j = k;
// Store fibonacci series into b[]
// array
b[m] = k;
}
i = 5;
System.out.println("\n" + "The Non-Fibonacci series that lies between 1 to "
+ no + " term of Fibonacci Series is: "+ "\n");
// Loop to calculate Non-Fibonacci
// series
for (int ans = 4; ans < b[no - 1]; ans++) {
if (ans != b[i])
// Print Non-Fibonacci Series
System.out.print(ans + " ");
else
i++;
}
}
}
// This Solution is contributed by shinjanpatra.
Python3
i = 0
j = 1
b = []
no = 10 # Range is 10
b.append(0)
b.append(1)
if(no <= 1): # Check if range is less equals to 1
print("You have enter a wrong range...")
elif(no <= 5 and no > 1): # check if range is greater than 1 and less equals to 5
print("\nThere is not any Non-Fibonacci series that lies between 1 to ",
no, " term of Fibonacci Series.")
else: # If range is greater than 5
for m in range(2, no): # Loop to calculate fibonacci series till range
k = i+j
i = j
j = k
b.append(k) # Store fibonacci series into list b
i = 5
print("\nThe Non-Fibonacci series that lies between 1 to ",
no, " term of Fibonacci Series is:")
for ans in range(4, b[no-1]): # Loop to calculate Non-Fibonacci series
if ans != b[i]:
print(ans, end=" ") # Print Non-Fibonacci Series
else:
i = i+1
C#
// C# code to implement the approach
using System;
class GFG {
public static void Main(string[] args)
{
int[] holes = { 21, 3, 6 };
int i = 0, j = 1, k, m, no = 10;
int[] b = new int[10];
// Range is 10
b[1] = 0;
b[2] = 1;
// Check if range is less equals to 1
if (no <= 1) {
Console.Write("You have enter a wrong range");
}
// check if range is greater than 1
// and less equals to 5
else if (no <= 5 && no > 1) {
Console.Write(
"\n"
+ "There is not any Non-Fibonacci series that lies between 1 to"
+ no + " term of Fibonacci Series.");
}
// If range is greater than 5
else {
// Loop to calculate fibonacci series till
// range
for (m = 2; m < no; m++) {
k = i + j;
i = j;
j = k;
// Store fibonacci series into b[]
// array
b[m] = k;
}
i = 5;
Console.WriteLine(
"\n"
+ "The Non-Fibonacci series that lies between 1 to "
+ no + " term of Fibonacci Series is: ");
// Loop to calculate Non-Fibonacci
// series
for (int ans = 4; ans < b[no - 1]; ans++) {
if (ans != b[i])
// Print Non-Fibonacci Series
Console.Write(ans + " ");
else
i++;
}
}
}
}
// This Solution is contributed by phasing17
JavaScript
<script>
// driver code
let i = 0, j = 1, k, m, no, b = new Array(10);
// Range is 10
no = 10;
b[1] = 0;
b[2] = 1;
// Check if range is less equals to 1
if (no <= 1) {
console.log("You have enter a wrong range");
}
// check if range is greater than 1
// and less equals to 5
else if (no <= 5 && no > 1) {
document.write("</br>","There is not any Non-Fibonacci series that lies between 1 to " + no + " term of Fibonacci Series.");
}
// If range is greater than 5
else {
// Loop to calculate fibonacci series till
// range
for (m = 2; m < no; m++) {
k = i + j;
i = j;
j = k;
// Store fibonacci series into b[]
// array
b[m] = k;
}
i = 5;
document.write("</br>","The Non-Fibonacci series that lies between 1 to " + no + " term of Fibonacci Series is: ","</br>");
// Loop to calculate Non-Fibonacci
// series
for (let ans = 4; ans < b[no - 1]; ans++) {
if (ans != b[i])
// Print Non-Fibonacci Series
document.write(ans , " ");
else
i++;
}
}
// This code is contributed by shinjanpatra
</script>
OutputThe Non-Fibonacci series that lies between 1 to 10 term of Fibonacci Series is:
4 6 7 9 10 11 12 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33
Time Complexity : O(n) , Auxiliary Space : O(n)
The above problem and solution are contributed by Hemang Sarkar.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem