Time Limit: 2000 ms Memory Limit : 131072KB
Description
Fibonacci numbers are well-known as follow:
Now given an interger N, please find outwhether N can be represented as the sum of several Fibonacci numbers in such away that the sum does not include any two consecutive Fibonacci numbers.
Input
Multiple test case, the first line is aninteger T (T <= 1000), Indicating the number of test cases.
Each test case is a line with an integer N(1<=N <= 109).
Output
One line per case. If the answer don’texist, output “-1”(without quotes). Otherwise, your answer should be formattedas “N=f1+f2+…+fn”. N indicates the given number and f1, f2, …, fn indicatingthe Fibonacci numbers in ascending order. If there are multiple ways, you canoutput any of them.
Sample
Input |
Output |
4 5 6 7 100 |
5=5 6=1+5 7=2+5 100=3+8+89 |
import java.util.*; import java.math.*; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Scanner cin = new Scanner(System.in); int[] f = new int[46]; f[1] = 1; f[2] = 2; for(int i = 3; i < 46; i++){//先求出斐波那契数 f[i] = f[i-1]+f[i-2]; } int[] vis = new int[46];//记录这个数是否被用到过 int[] flag = new int[46];//存储符合的数 int t = cin.nextInt();//代表测试输入的行数 while((t--) != 0){ int n = cin.nextInt();//代表输入的数 System.out.print(n+"="); int k = 1;//存储符合的数个数 for(int i = 45; i > 0; i--){ if(f[i] <= n&& vis[i-1] == 0 && vis[i+1] == 0){//从等于n或是小于n考试进行查找,并且判断这个数是否被走过,并且这个数不可能是相邻两个斐波那契数 vis[i] = 1; n = n-f[i]; flag[k++] = f[i]; } } for(int i = k-1; i > 0; i--){//倒叙输出 if(i == 1){ System.out.print(flag[1]); break; } System.out.print(flag[i]+"+"); } } } }