Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Find the Sum of Fibonacci Numbers in a Range

Basic Acceptance 84.68% Points 10.00

You are given two integers L and R. Your task is to return the sum of all Fibonacci numbers that lie within the inclusive range [L, R].

The Fibonacci sequence starts with 0 and 1. Each subsequent number is calculated as the sum of the two preceding numbers. Include every Fibonacci number that falls between L and R, including both endpoints. If no Fibonacci number lies in the given range, return 0.

Examples
Example 1

Input: L = 1, R = 10

Output: 20

Explanation: The Fibonacci numbers 1, 1, 2, 3, 5, 8 lie within the range. Their sum is 20.

Example 2

Input: L = 5, R = 20

Output: 26

Explanation: The Fibonacci numbers 5, 8, and 13 lie within the range. Their sum is 26.

Example 3

Input: L = 100, R = 120

Output: 0

Explanation: No Fibonacci number lies within the range, so the sum is 0.

Constraints
  • 0 <= L <= R <= 1018
Companies
Samsung Expedia
Topics
Introduction Data Structures Basics
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions