Algorithm problem---k-order Fibonacci sequence

Source: Internet
Author: User

#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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.