wasAsked.

recursively find sum of N Fibonacci numbers. 0,1,1,2,3,5,8,13,21,....

Mphasis · Role not specified · technical

Published

Year not specified · C#

Community answers

Posted by wasAsked editorial collection

A direct recursive Fibonacci implementation is exponential because it recomputes the same values. Memoization makes it O(n), but an iterative solution avoids recursion depth and is simpler. Example: static long Fibonacci(int n) { if (n < 0) throw new ArgumentOutOfRangeException(nameof(n)); checked { long a = 0, b = 1; for (var i = 0; i < n; i++) (a, b) = (b, a + b); return a; } } If recursion is required, pass a dictionary cache. long overflows after F(92), so use BigInteger for larger inputs and validate an upper limit when this is exposed through an API.

Backbencher Developer · · 0 likes

The Fibonacci sequence starts 0, 1, and each next number is the sum of the previous two: 0, 1, 1, 2, 3, 5, 8, 13, 21... Sum of the first N Fibonacci numbers using recursion Simple recursive version (clear, but exponential time): static long Fib(int n) => n < 2 ? n : Fib(n - 1) + Fib(n - 2); static long SumFib(int count) => count <= 0 ? 0 : Fib(count - 1) + SumFib(count - 1); Console.WriteLine(SumFib(9)); // 0+1+1+2+3+5+8+13+21 = 54 This recomputes the same values many times: Fib is O(2^n), so it becomes very slow beyond about n = 40. Recursive with memoisation (O(n)): static long SumFibMemo(int count) { var memo = new Dictionary<int, long>(); long Fib(int n) { if (n < 2) return n; if (memo.TryGetValue(n, out var cached)) return cached; return memo[n] = Fib(n - 1) + Fib(n - 2); } long Sum(int c) => c <= 0 ? 0 : Fib(c - 1) + Sum(c - 1); return Sum(count); } Single recursive pass carrying state (tail-recursive style, O(n)): static long SumFibCarry(int remaining, long current = 0, long next = 1, long sum = 0) => remaining == 0 ? sum : SumFibCarry(remaining - 1, next, current + next, sum + current); Console.WriteLine(SumFibCarry(9)); // 54 Mathematical shortcut worth mentioning The sum of the first N Fibonacci numbers F(0) through F(N-1) equals F(N+1) - 1. For N = 9: F(10) - 1 = 55 - 1 = 54. Iterative version (best in production, no stack overflow risk): static long SumFibIterative(int count) { long a = 0, b = 1, sum = 0; for (int i = 0; i < count; i++) { sum += a; (a, b) = (b, a + b); } return sum; } Discussion points - C# does not guarantee tail-call optimisation, so deep recursion can cause StackOverflowException; iterative code is safer for large N. - long overflows after about F(92); use checked arithmetic or BigInteger for larger values. - Clarify with the interviewer whether "N numbers" starts at 0 or 1 — it changes the answer by one term.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics