Algorithm
Problem Name: beecrowd | 1151
Problem Link: https://www.beecrowd.com.br/judge/en/problems/view/1151
Easy Fibonacci
Adapted by Neilor Tonin, URI Brazil
Timelimit: 1
The following sequence of numbers 0 1 1 2 3 5 8 13 21 ... is known as the Fibonacci Sequence. Thereafter, each number after the first 2 is equal to the sum of the previous two numbers. Write an algorithm that reads an integer N (N < 46) and that print the first N numbers of this sequence.
Input
The input file contains an integer number N (0 < N < 46).
Output
The numbers should be printed on the same line, separated by a blank space. There is no space after the last number.
Input Sample | Output Sample |
5 |
0 1 1 2 3 |
Code Examples
#1 Code Example with C++ Programming
Code -
C++ Programming
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin >> n;
int arr[50];
arr[0] = 0;
arr[1] = 1;
for (int i = 2; i < n; i++){
arr[i] = arr[i-1] + arr[i - 2];
}
for (int i = 0; i < n; i++){
if (i == (n - 1)){
cout << arr[i] << endl;
}
else{
cout << arr[i] << " ";
}
}
return 0;
}
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with Java Programming
Code -
Java Programming
import java.io.IOException;
import java.util.Scanner;
public class Main{
public static void main(String[] args) throws IOException{
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int arr[] = new int[50];
arr[0] = 0;
arr[1] = 1;
for (int i = 2; i < n; i++){
arr[i] = arr[i-1] + arr[i - 2];
}
for (int i = 0; i < n; i++){
if (i == (n - 1)){
System.out.println(arr[i]);
}
else{
System.out.printf("%d ", arr[i]);
}
}
}
}
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with Javascript Programming
Code -
Javascript Programming
var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var lines = input.split('\n');
var n = parseInt(lines.shift());
var arr = [0, 1];
for (var i = 2; i < n; i++){
arr.push(arr[i-1] + arr[i - 2]);
}
for (var i = 0; i < n; i++){
if (i === (n - 1)){
console.log(arr[i]);
}
else{
process.stdout.write(arr[i]+ " ");
}
}
Copy The Code &
Try With Live Editor
Input
Output
#4 Code Example with Python Programming
Code -
Python Programming
n = int(input())
arr = list()
arr.append(0)
arr.append(1)
for i in range(2, n):
arr.append(arr[i-1] + arr[i - 2])
for i in range(len(arr)):
if (i == (n - 1)):
print(arr[i])
else:
print(arr[i], end=" ")
Copy The Code &
Try With Live Editor
Input
Output