JAVA:斐波那契递归和非递归函数

huangapple 未分类评论58阅读模式
英文:

JAVA: Fibonacci Recursive and Non-Recursive Function

问题

static int recursiveMethod(int num)
{
if (num <= 1)
return num;
return recursiveMethod(num-1) + recursiveMethod(num-2);
}

static int nonRecursiveMethod(int num) {
if (num == 0) {
return 0;
}

if (num == 1) {
    return 1; 
} 
int first = 0; 
int second = 1; 
int nth = 1; 
for (int i = 2; i <= num; i++) { 
    nth = first + second;
    first = second;
    second = nth;
} 
return nth;

}

For summary:
Example I inputted 6 as my nth value. Then the outputs are
RECURSIVE: 8 then
NON-RECURSIVE: 1 1 2 3 5 8

英文:

Hi there sorry for this noob question. I'm Mario and may I ask if my program is correct for recursive and non-recursive function for Fibonacci Secquence nth Value.

static int recursiveMethod(int num) 
{ 
if (num &lt;= 1) 
   return num; 
return recursiveMethod(num-1) + recursiveMethod(num-2); 
}

static int nonRecursiveMethod(int num) { 
	if (num == 0) { 
		return 0; 
	}
	
	if (num == 1) {
		return 1; 
	} 
	int first = 0; 
	int second = 1; 
	int nth = 1; 
	for (int i = 2; i &lt;= num; i++) { 
		nth = first + second;
		first = second;
		second = nth;
	} 
	return nth;
}

For summary:
Example I inputted 6 as my nth value. Then the outputs are
RECURSIVE: 8 then
NON-RECURSIVE: 1 1 2 3 5 8

Is that correct?

答案1

得分: 0

调用nonRecursiveMethod将产生与调用recursiveMethod相同的输出。 结果是正确的,尽管recursiveMethod对于大数而言效率较低,因为它会一遍又一遍地计算较小数字的结果。

英文:

Calling nonRecursiveMethod will produce the same output as calling recursiveMethod. The result is correct, recursiveMethod is inefficient for big numbers, though, because it will compute results for lower numbers again and again.

答案2

得分: 0

是的,这两种方法都可以。我想在这里提出的建议是,与其为每个“num”调用函数,不如预先计算并存储这些值(动态规划)。

英文:

yeah both the approaches are fine. What I would like to suggest here is rather than calling function for every "num" you can pre-compute and store the values(Dynamic Programming).

huangapple
  • 本文由 发表于 2020年4月3日 19:30:27
  • 转载请务必保留本文链接:https://java.coder-hub.com/61010880.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定