Give a number N, print alternate fibonacci numbers till n-th Fibonacci.
Examples:
Input : N = 7
Output : 0 1 3 8
Input : N = 15
Output : 0 1 3 8 21 55 144 377
Read method 2 in the following article : fibonacci number
Approach:Using dynamic programming approach. Keep storing the previously calculated fibonacci numbers and using the previous two to store the next fibonacci number.
C++
#include <bits/stdc++.h>
using namespace std;
void alternateFib(int n)
{
if (n < 0)
return;
int f1 = 0;
int f2 = 1;
cout << f1 << " ";
for (int i = 2; i <= n; i++) {
int f3 = f2 + f1;
if (i % 2 == 0)
cout << f3 << " ";
f1 = f2;
f2 = f3;
}
}
int main()
{
int N = 15;
alternateFib(N);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static void alternateFib(int n)
{
if (n < 0)
return;
int f1 = 0;
int f2 = 1;
System.out.print(f1 + " ");
for (int i = 2; i <= n; i++)
{
int f3 = f2 + f1;
if (i % 2 == 0)
System.out.print(f3 + " ");
f1 = f2;
f2 = f3;
}
}
public static void main (String[] args)
{
int N = 15;
alternateFib(N);
}
}
|
Python3
def alternateFib(n):
if (n < 0):
return -1;
f1 = 0;
f2 = 1;
print(f1, end = " ");
for i in range(2, n + 1):
f3 = f2 + f1;
if (i % 2 == 0):
print(f3, end = " ");
f1 = f2;
f2 = f3;
N = 15;
alternateFib(N);
|
C#
using System;
class GFG
{
static void alternateFib(int n)
{
if (n < 0)
return;
int f1 = 0;
int f2 = 1;
Console.Write(f1 + " ");
for (int i = 2; i <= n; i++)
{
int f3 = f2 + f1;
if (i % 2 == 0)
Console.Write(f3 + " ");
f1 = f2;
f2 = f3;
}
}
public static void Main ()
{
int N = 15;
alternateFib(N);
}
}
|
PHP
<?php
function alternateFib($n)
{
if ($n < 0)
return;
$f1 = 0;
$f2 = 1;
echo $f1 . " ";
for ($i = 2; $i <= $n; $i++)
{
$f3 = $f2 + $f1;
if ($i % 2 == 0)
echo $f3 . " ";
$f1 = $f2;
$f2 = $f3;
}
}
$N = 15;
alternateFib($N);
?>
|
Javascript
<script>
function alternateFib(n)
{
if (n < 0)
return;
var f1 = 0;
var f2 = 1;
document.write(f1 + " ");
for(i = 2; i <= n; i++)
{
var f3 = f2 + f1;
if (i % 2 == 0)
document.write(f3 + " ");
f1 = f2;
f2 = f3;
}
}
var N = 15;
alternateFib(N);
</script>
|
Output:
0 1 3 8 21 55 144 377
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!
Last Updated :
28 Apr, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...