
Problem
Solution
Submissions
Fibonacci Numbers
Certification: Basic Level
Accuracy: 100%
Submissions: 4
Points: 10
Write a C++ program that prints all Fibonacci numbers within a specified limit. The Fibonacci sequence starts with 0 and 1, and each subsequent number is the sum of the two preceding ones.
Example 1
- Input: limit = 50
- Output: "0, 1, 1, 2, 3, 5, 8, 13, 21, 34"
- Explanation:
- Step 1: Initialize the first two Fibonacci numbers as 0 and 1.
- Step 2: Generate subsequent Fibonacci numbers by adding the two previous numbers.
- Step 3: Continue the process until the generated number exceeds the given limit.
- Step 4: Print all Fibonacci numbers less than or equal to the limit.
Example 2
- Input: limit = 5
- Output: "0, 1, 1, 2, 3, 5"
- Explanation:
- Step 1: Initialize the first two Fibonacci numbers as 0 and 1.
- Step 2: Generate subsequent Fibonacci numbers: 0+1=1, 1+1=2, 1+2=3, 2+3=5.
- Step 3: The next Fibonacci number would be 3+5=8, which exceeds the limit of 5.
- Step 4: Print all Fibonacci numbers less than or equal to the limit: 0, 1, 1, 2, 3, 5.
Constraints
- 0 ≤ limit ≤ 10^9
- Input is a positive integer
- Time Complexity: O(n), where n is the number of Fibonacci numbers up to the limit
- Space Complexity: O(1) excluding the output space
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Initialize the first two Fibonacci numbers (0 and 1)
- Use a loop to generate the next Fibonacci number by adding the previous two
- Stop when the next Fibonacci number exceeds the given limit
- Handle the special case when the limit is less than 1