Do you know the Fibonacci number? Here is a definition of it:
F1 = 1
F2 = 2
Fn+1 = fn+fn-1, here n>1
Each positive integer x can be written as the sum of different Fibonacci numbers, thus implying the existence of the number K and B1, B2, ..., BK, making x=b1*f1+ ... + bi*fi+ ... +bk*fk, where bk = 1,bi (1≤i < K) is 0 or 1. In short, we can write as: b (x) = (BK, Bk-1, ..., B1). For the expression to be unique, we ask for all i > 1,bi * bi-1 = 0.
With Fibonacci numbers, we can convert the kilometer unit distance x to the corresponding mile unit distance y, first, with the Fibonacci system representing B (x) writing down X. Second, move the number in B (x) Right one (last delete) and get B (y). Third, calculate the sum from B (y) to figure out Y.
For example, the number 42 is represented by the Fibonacci system as: (1,0,0,1,0,0,0,0). In the second step, we get (1,0,0,1,0,0,0) by moving right. In the third step, we calculate 0*1 + 0*2 + 0*3 + 1*5 + 0*8 + 0*13 + 1*21 = 26.
Below please write a program, according to the above algorithm to convert kilometers into miles.
Enter the number of distances (t<25000) that the first line contains T, which need to be converted. Each of the following T-lines contains an integer distance of x (2 < x < 25000) kilometers.
For each distance x km, the output calculates the Y mile.
5
42
100
180
300
360
26
62
111
185
222
#include <iostream>using namespace STD;intfa[ at]={0,1,2};voidFabintn= at){intI for(i=3; i<=n;i++) fa[i]=fa[i-2]+fa[i-1];}intMain () {inti,n,x,j,sum,visit[ at]; Fab ();scanf("%d", &n); for(i=1; i<=n;i++) {memset(Visit,0,sizeof(visit)); sum=0;scanf("%d", &x); for(j= +; j>=1; j--) {if(sum+fa[j]<x) {visit[j]=1; sum=sum+fa[j];}Else if(sum+fa[j]==x) {visit[j]=1; Break; }} x=0; for(j=1; j<= +; j + +) visit[j]=visit[j+1]; for(j=1; j<= +; j + +)if(Visit[j]) x=x+fa[j];printf("%d\n", x); }return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Fibonacci Number Applications