Fibonacci Series
Print the first n numbers of the Fibonacci series, where each number is the sum of the previous two.
Sample input
8
Sample output
0 1 1 2 3 5 8 13
Solution
n = 8
a, b = 0, 1
out = []
for _ in range(n):
out.append(a)
a, b = b, a + b
print(*out)
let n = 8, a = 0, b = 1;
const out = [];
for (let i = 0; i < n; i++) {
out.push(a);
[a, b] = [b, a + b];
}
console.log(out.join(" "));
public class Main {
public static void main(String[] args) {
int n = 8, a = 0, b = 1;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(a);
if (i < n - 1) sb.append(" ");
int next = a + b;
a = b;
b = next;
}
System.out.println(sb.toString());
}
}
fun main() {
val n = 8
var a = 0
var b = 1
val out = mutableListOf<Int>()
repeat(n) {
out.add(a)
val next = a + b
a = b
b = next
}
println(out.joinToString(" "))
}
let n = 8
var a = 0, b = 1
var out = [String]()
for _ in 0..<n {
out.append(String(a))
let next = a + b
a = b
b = next
}
print(out.joined(separator: " "))
void main() {
int n = 8, a = 0, b = 1;
List<int> out = [];
for (int i = 0; i < n; i++) {
out.add(a);
int next = a + b;
a = b;
b = next;
}
print(out.join(' '));
}
#include <iostream>
using namespace std;
int main() {
int n = 8, a = 0, b = 1;
for (int i = 0; i < n; i++) {
cout << a;
if (i < n - 1) cout << " ";
int next = a + b;
a = b;
b = next;
}
cout << endl;
return 0;
}
#include <stdio.h>
int main() {
int n = 8, a = 0, b = 1;
for (int i = 0; i < n; i++) {
printf("%d", a);
if (i < n - 1) printf(" ");
int next = a + b;
a = b;
b = next;
}
printf("\n");
return 0;
}