Y. Easy Fibonacci
time limit per test
1 secondmemory limit per test
256 megabytesinput
standard inputoutput
standard outputGiven a number N. Print first N numbers of the Fibonacci sequence.
Note: In order to create the Fibonacci sequence use the following function:
- fib(1) = 0.
- fib(2) = 1.
- fib(n) = fib(n - 1) + fib(n - 2).
Input
Only one line containing a number N (1 ≤ N ≤ 45).
Output
Print the first N numbers from the Fibonacci Sequence .
Example
input
Copy
7
output
Copy
0 1 1 2 3 5 8
Note
For more information visit Fibonacci: https://www.mathsisfun.com/numbers/fibonacci-sequence.html.
solution:
#include<iostream> using namespace std; int main() { int n, t1 = 0, t2 = 1, sum = 0; cin >> n; for (int i = 1; i <= n; i++) { if (i == 1) cout << t1 << " "; else if (i == 2) cout << t2 << " "; else { sum = t1 + t2; cout << sum << " "; t1 = t2; t2 = sum; } } return 0; }
No comments:
Post a Comment