我被要求确定可以在我的系统上显示的最大的斐波纳契数,我想知道如何做到这一点..
这是我的简单应用程序,它决定了第n个斐波纳契数
import java.util.Scanner;
public class FibonacciTest
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.printf("please enter the nth fibonacci number: ");
int n = input.nextInt();
System.out.printf("%d\n", fibonacci(n));
}// end main
public static int fibonacci(int n)
{
// determines nth fibonacci number
int fib = 1;
int temp = 0;
if (n == 1)
return 0;
else
{
for (int i = 2; i < n; i++)
{
int last = fib;
fib += temp;
temp = last;
}
return fib;
}
}// end fibonacci
}
Run Code Online (Sandbox Code Playgroud)
确定可以在我的系统上显示的最大斐波那契数
为此,您需要使用BigInteger
运行此操作直到您的应用程序停止,因为您的资源已用完.
public static void main(String... args) {
BigInteger a = BigInteger.ONE;
BigInteger b = BigInteger.ONE;
String last = null;
try {
for (long count = 1; ; count++) {
BigInteger c = a.add(b);
last = c.toString();
a = b;
b = c;
if (count % 10000 == 0)
System.out.println("... " + count);
}
} catch (Throwable e) {
System.out.println("The largest value which was calculated was");
System.out.println(last);
}
}
Run Code Online (Sandbox Code Playgroud)
我会首先尝试使用少量内存,例如 -mx16m
更新:即使限制为16 MB,它也计算了13K项并仍在运行.
intJava中最大的斐波纳契数:
public class FibonacciTest
{
public static void main(String[] args)
{
System.out.printf("%d\n", largestFibonacciInt());
}
public static int largestFibonacciInt()
{
int temp;
int last = 1;
int fib = 1;
while (fib + last > fib) {
temp = fib;
fib += last;
last = temp;
}
return fib;
}
}
Run Code Online (Sandbox Code Playgroud)
您也可以long通过简单地替换所有出现的内容来执行此操作int.
| 归档时间: |
|
| 查看次数: |
7309 次 |
| 最近记录: |