简体   繁体   English

如何打印Fibonacci系列并在堆栈溢出发生之前停止-JAVA

[英]How to print Fibonacci Series and stop before stack overflow occurs - JAVA

I have been asked the above question / task in an job interview. 在工作面试中有人问我上述问题/任务。

Is there any way to stop the series just before overflow occurs? 有什么办法可以在溢出发生之前停止该系列?

At first its seemed weird to me, i couldn't see a way where someone can predict 刚开始我觉得很奇怪,我看不到有人可以预测的方式

when is going to take place, but then my thought was to check if the current 什么时候会发生,但是我当时的想法是检查当前

value < Integer.MAX_VALUE. 值<Integer.MAX_VALUE。

What do you think? 你怎么看? can anyone suggest a solution to my question? 谁能为我的问题提出解决方案?

thanks in advanced. 提前致谢。

Write your logic for Fibonacci series and add a condition before storing the value which will check free memory using 写出斐波那契数列的逻辑,并在存储值之前添加一个条件,该值将使用以下方法检查可用内存

Runtime.getRuntime().freeMemory();

Once free memory reaches to zero break the loop. 一旦可用内存达到零,就打破循环。 This should solve your overflowing issue 这应该可以解决您的问题

I think this is a much more theoretical question rather than one with actual solution. 我认为这是一个理论问题,而不是实际解决方案。

Lets define the Fib method to be: 让我们将Fib方法定义为:

public static int fib(n){
    if (n<=2)
        return 1;
    return fib(n-1) + fib(n-2);

Now by calling fib for n=100 for example, could resolve in a stack over flow exception. 现在,例如,通过为n = 100调用fib,可以解决栈溢出异常。 If some how we simplify the way the stack works we could actually ask the function to check the "space" left in stack and hold to it's value if it's equivalent to 0. 如果我们简化了堆栈的工作方式,我们实际上可以要求函数检查堆栈中剩余的“空格”,并保持其等于0的值。

Hope it helps! 希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM