我想查看12位数字,如果它们属于Fibonacci系列。我写了下面的代码,但似乎效率低下,我遇到了超时错误。我怎样才能优化我的代码?
Scanner sc=new Scanner(System.in);
List<Long> test_list=new ArrayList<>();
List<String> final_list=new ArrayList<>();
long cases=sc.nextLong();
for(int i=0;i<cases;i++)
{
long input=sc.nextLong();
test_list.add(input);
}
for(int j=0;j<test_list.size();j++)
{
long check_number=test_list.get(j);
long a=0l,b=1l,c=0l;
while(c<check_number)
{
c=a+b;
a=b;
b=c;
}
if(c == check_number)
{
final_list.add("IsFibo");
}
else
{
final_list.add("IsNotFibo");
}
}
for(String s:final_list)
{
System.out.println(s);
}
答案 0 :(得分:1)
12位斐波那契数字的简易硬编码解决方案。
long f55 = 139583862445L;
long f56 = 225851433717L;
long f57 = 365435296162L;
long f58 = 591286729879L;
long f59 = 956722026041L;
for(int j=0;j<test_list.size();j++)
{
long n=test_list.get(j);
if(n == f55 || n == f56 || n == f57 || n == f58 || n == f59)
{
final_list.add("IsFibo");
}
else
{
final_list.add("IsNotFibo");
}
}
答案 1 :(得分:0)
您可以这样做:
Scanner sc = new Scanner(System.in);
List<Long> fibonaci = new ArrayList<Long>(); // Added to store already calculated fibo number
fibonaci.add(0L);
fibonaci.add(1L);
List<Long> test_list = new ArrayList<>();
List<String> final_list = new ArrayList<>();
long cases = sc.nextLong();
for (int i = 0; i < cases; i++) {
long input = sc.nextLong();
test_list.add(input);
}
for (int j = 0; j < test_list.size(); j++) {
long check_number = test_list.get(j);
long a = fibonaci.get(fibonaci.size()-2), b = fibonaci.get(fibonaci.size() - 1), c = 0l;
if (check_number > b) { //To Check whether last number in fibo is less than input
while (c < check_number) {
c = a + b;
fibonaci.add(c);
a = b;
b = c;
}
}
if (c == check_number || fibonaci.contains(check_number)) {
final_list.add("IsFibo");
} else {
final_list.add("IsNotFibo");
}
}
for (String s : final_list) {
System.out.println(s);
}
我做了什么: