Practice › Basics
Fibonacci Series
Easy · Basics · Asked at TCS, Infosys, Wipro, Accenture, Cognizant
Print the first n numbers of the Fibonacci series, which starts 0 1 and continues with each number being the sum of the two before it: 0 1 1 2 3 5 8 ….
Input
A single integer n.
Output
The first n Fibonacci numbers, space-separated.
Constraints
- 1 ≤ n ≤ 90
Keep only the last two numbers. F(89) is about 1.8 × 10^18, so use 64-bit integers.
Example 1
Input
7
Output
0 1 1 2 3 5 8
Example 2
Input
1
Output
0
Hints
- Each number needs only the two before it.
- Start with 0 and 1.
- F(89) is above 10^18 — use 64-bit integers.
Approach
Keep a = 0 and b = 1. Print a, then move forward: (a, b) = (b, a + b), n times in total. No array is needed.
Complexity: O(n) time · O(1) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
long long a = 0, b = 1;
for (int i = 0; i < n; i++) {
cout << a << (i + 1 < n ? ' ' : '\n');
long long c = a + b;
a = b;
b = c;
}
return 0;
}Python solution
n = int(input())
a, b = 0, 1
out = []
for _ in range(n):
out.append(a)
a, b = b, a + b
print(*out)Java solution
import java.util.*;
public class Main {
public static void main(String[] args) {
int n = new Scanner(System.in).nextInt();
long a = 0, b = 1;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(a).append(i + 1 < n ? " " : "\n");
long c = a + b;
a = b;
b = c;
}
System.out.print(sb);
}
}