Home > Software design >  Can someone tell me on how to print Fibonacci series, but the user will choose the start and the end
Can someone tell me on how to print Fibonacci series, but the user will choose the start and the end

Time:01-16

Like the user chooses 55 as the starting point and 987 as the end and the series will be like The series is: 55, 89, 144, 233, 377, 610, 987

CodePudding user response:

You could just calculate the Fibonacci sequence starting from 1 to the endpoint and once you reach the start point, you can start adding the numbers to an empty array. This weeds out all the ones that aren't necessary and accomplishes the task.

CodePudding user response:

You can use in dynamic programming approach save the first 2 numbers in the series in this example num1 = 55, num2 = 89 and sum = num1 num2 you can get num2 by running fib on dynamic programming approach till it will get to the start value limit(starting point)

public int fibWithLimit(int start,int start2 int end) {
int num1 = start, num2= start2, sum= num1  num2;
while(sum < end) {
    num1= num2
    num2 = sum;
    sum = num1  num2;
  }
 return sum;
}

CodePudding user response:

You can use a closed form expression of the n-th Fibonacci number which is given by (sorry, because of lack of reputation I can not insert a math formula, only a link to that formula at google chart)

https://chart.googleapis.com/chart?cht=tx&chl=F_n=\frac{1}{\sqrt5}\left[\left(\frac{1+\sqrt{5}}{2}\right)^{n}-\left(\frac{1-\sqrt{5}}{2}\right)^{n}\right]

Also there are some details with examples in R which could be useful https://fabiandablander.com/r/Fibonacci.html

  •  Tags:  
  • Related