Question

I just start to learn programming and here is a problem about fibonacci sequence:

It is asked to make a function with parameter k(means k-order of fibonacci) and parameter n(means the n th member of sequence) and use that function to get the m th member of a k-order sequence.

f0 = 0, f1 =0, ....fk-2 =0, fk-1=1;
when n=k, k+1,...
fn= fn-1+fn-2+....+fn-k;     n=k,k+1,....

(letters and numbers on right-side of f are subscripts which mean the n th member, n-1 th member..)

following is my code:

int Fibonacci(int k, int n){
int result=0;
if (n==k-1) return 1;
if (n<k-1) return 0;
if (n>=k){
    for(int i=n-1; i>i-k-1;--i){
        result+=Fibonacci(k,i);
        cout<<result<<endl;
    }
return result;
}

}


new version

int result=0;
int Fibonacci(int k, int n){
if (n==k-1) return 1;
if (n<k-1) return 0;
if (n>=k){
    for(int i=n-1; i>n-k-1;--i){
        result+=Fibonacci(k,i);
        cout<<result<<endl;
    }
return result;
}
}

my question is why this code cannot come out correct answer? there should be some problems in the loop but I cannot find them. Will someone help me?

Was it helpful?

Solution

for(int i=n-1; i>i-k-1;--i)

i will pretty much always be greater than i-k-1

Maybe you mean for(int i=n-1; i>n-k-1;--i), but you should check.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top