Write a program to print the Fibonacci series.
Example 1:
Input:num=10
Output:0 1 1 2 3 5 8 13 21 34
Approach
Java
public class FibonacciSeries {public static void main(String[] args) {int num = 10;String series = fibonacciSeries(num);System.out.println("Febonacci Series " + series);}private static String fibonacciSeries(int num) {String series = "";int f0 = 0;int f1 = 1;series = "0 1";int n = 1;for (int i = 2; i < num; i++) {n = f0 + f1;series += " " + n;f0 = f1;f1 = n;}return series;}}
C++
#include <bits/stdc++.h>using namespace std;//Function to find fibonacci//seriesvector<int> fibonacciSeries(int num){vector<int> fibo;fibo.push_back(0);if(num==1)return fibo;fibo.push_back(1);int a=0,b=1;int temp;for(int i=2;i<num;i++){temp=a+b;fibo.push_back(temp);a=b;b=temp;}return fibo;}int main(){int num=10;vector<int> fiboSeries=fibonacciSeries(num);cout<<"Fibonacci Series is ";for(int i=0;i<fiboSeries.size();i++)cout<<fiboSeries[i]<<" ";return 0;}//Time Complexity: O(n)
No comments:
Post a Comment