Tutorialspoint
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
Variables and Data TypesControl StructuresDropboxPhillips
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Define a function generate_fibonacci that takes a limit value.

 Step 2: Initialize a vector to store the Fibonacci numbers.
 Step 3: Handle base cases by adding 0 and 1 to the vector if the limit allows.
 Step 4: Use variables a=0 and b=1 to keep track of the last two Fibonacci numbers.
 Step 5: Use a while loop to calculate each new Fibonacci number as the sum of the previous two.
 Step 6: Break the loop when the calculated number exceeds the given limit.
 Step 7: Return the vector containing all Fibonacci numbers up to the limit.

Submitted Code :