#include <iostream>#include<cstdio>#include<stdlib.h>#include<algorithm>using namespacestd;intMain () {inta[ -]; intK, M; while(1) {cout<<"Enter the order k and the Convention constant Max. K and Max are separated by spaces. "<<Endl; CIN>> k >>m; inti; for(i =0; I < K-1; i++) A[i]=0; A[k-1] =1; A[K]=1; intn = k +1; if(M = =0) {cout<< K-2<<Endl; cout<<1<<Endl; return 0; } if(M = =1) {cout<< k <<Endl; cout<<1<<Endl; return 0; } while(A[n-1] <=m) {A[n]=2* A[n-1]-A[n-k-1]; N++; } cout<< N-2<<Endl; cout<< A[n-2] <<Endl; } return 0;}
View Code
Topic:
the first n+1 term in the K-order Fibonacci sequence is written by the cyclic queue ( F 1, F2,..., fn) algorithm, required to meet F N≤ (less than or equal to)Max, and Fn +1>max
Max is a constant of a convention. Note: The capacity of the loop queue is K, when the algorithm ends, the element left in the queue is the last K term in the K-order Fibonacci sequence .
inputEnter a K (2<= K <= 100) representing the order and max (0 <= Max <= 100000) that represents a constant. OutputThe output satisfies the condition of N (n is counted from 0), takes one row, and the value of the nth item, which is a row; outputs a carriage return character.Input Sample4 10000Output Sample17 5536
Ideas:
The known K-order Fibonacci sequence is defined as: F0 = 0, f1 = 0, ..., fk-2 = 0, fk-1 = 1;
and fn = fn-1 + fn-2 + ... + fn-k, n = k, k + 1, ...
Simplify and get an iterative formula:①:f (M) =f (m-1) +f (m-2) +...+f (m-k) ②:f (m-1) =f (m-2) +f (m-3) +...+f (m-k-1) ①-②: F (M)-F (m-1) =f (m-1)-F (m-k-1)
f (m) =2f (M-1)-F (m-k-1)
Algorithm problem---k-order Fibonacci sequence