Summing n terms of a Fibonacci Sequence
Code java:
public class FibonacciSequence extends Sequence implements Sequenceable{
private double secondTerm;
public FibonacciSequence(){
super(1);
this.secondTerm = 1;
}
/**
*
* @param first first term of fib sequence
* @param second second term of fib sequence
*/
public FibonacciSequence(double first, double second){
super(first);
this.secondTerm = second;
}
/**
*
* @param n
* @return
*/
@Override
public double getNthTerm(int n) {
double term1 = super.getFirstTerm();
double term2 = this.secondTerm;
double nTerm = 0;
if(n == 1){
return term1;
}
else if (n == 2){
return term2;
}
else{
for(int i = 3;i <= n ; i++){
nTerm = term1 + term2;
term1 = term2;
term2 = nTerm;
}
return nTerm;
}
}
/**
*
* @param n
* @return
*/
@Override
public double sumNTerms(int n) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
I know the Fibonacci sequence is firstTerm + secondTerm = thirdTerm, secondTerm + thirdTerm = fourthTerm and so on. I am confused on how to write the syntax to sum n number of terms.
Re: Summing n terms of a Fibonacci Sequence
recursion is common in a solution to this type of problem
There seems to be a starting point to the system, and the same process repeated over and over without changing the process.
The starting point defines your base case(s) and the repeated process defines what is to be updated causing you to eventually reach a base case.