Given an integer N. The task is to find the Nth odd Fibonacci number.
The odd number fibonacci series is as:
1, 1, 3, 5, 13, 21, 55, 89, 233, 377, 987, 1597………….and so on.
Note: In the above series we have omitted even terms from the general fibonacci sequence.
Examples:
Input: N = 3
Output: 3
Input: N = 4
Output: 5
Approach:
On observing carefully, it can be deduced that every third Fibonacci number is even, so the Nth odd Fibonacci number is the {(3*N+1)/2}th term in the general Fibonacci sequence.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int oddFib(int n)
{
n = (3 * n + 1) / 2;
int a = -1, b = 1, c, i;
for (i = 1; i <= n; i++) {
c = a + b;
a = b;
b = c;
}
return c;
}
int main()
{
int n = 4;
cout << oddFib(n);
return 0;
}
|
Java
class GFG
{
static int oddFib(int n)
{
n = (3 * n + 1) / 2;
int a = -1, b = 1, c = 0, i;
for (i = 1; i <= n; i++)
{
c = a + b;
a = b;
b = c;
}
return c;
}
public static void main (String[] args)
{
int n = 4;
System.out.println(oddFib(n));
}
}
|
Python3
def oddFib(n):
n = (3 * n + 1) // 2
a = -1
b = 1
c = 0
for i in range(1, n + 1):
c = a + b
a = b
b = c
return c
n = 4
print(oddFib(n))
|
C#
using System;
class GFG
{
static int oddFib(int n)
{
n = (3 * n + 1) / 2;
int a = -1, b = 1, c = 0, i;
for (i = 1; i <= n; i++)
{
c = a + b;
a = b;
b = c;
}
return c;
}
public static void Main (String[] args)
{
int n = 4;
Console.WriteLine(oddFib(n));
}
}
|
Javascript
<script>
function oddFib(n)
{
n = (3 * n + 1) / 2;
var a = -1, b = 1, c, i;
for (i = 1; i <= n; i++) {
c = a + b;
a = b;
b = c;
}
return c;
}
var n = 4;
document.write(oddFib(n));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!