[英]Tail Recursion java
I am working on finding the largest prime factor of any given number. 我正在寻找任何给定数字中最大的素数。 The code below works fine for most numbers until I input the number I want which is 600851475143. Once I do this I get stack overflow.
下面的代码适用于大多数数字,直到我输入所需的数字600851475143。执行此操作后,我会得到堆栈溢出。 I have been reading up on tail recursion and from what I know I should have implemented it right.
我一直在阅读尾递归,据我所知,我应该正确地实现它。 Yet, I still receive the stack overflow error despite it.
但是,尽管如此,我仍然收到堆栈溢出错误。 Where am I going wrong when it comes to implementing tail recursion?
实施尾递归时,我哪里出错了?
import java.util.Scanner;
public class LargestPrimeFactor
{
static long number;
static long answer;
public static void main(String[] args)
{
System.out.println( "Enter number to find its largest prime factor");
Scanner input = new Scanner(System.in);
number = input.nextLong();
answer = largestPrime(number);
System.out.println("The largest prime of " + number + " is " + answer);
}
private static long largestPrime(long n)
{
n = n-1;
if(n % 2 != 0 & number % n == 0 )
{
return n;
}
else
{
return largestPrime(n);
}
}
}
First, in the if condition you're doing &
when you probably meant to do &&
. 首先,在if条件下,您正在做
&
,而您可能打算做&&
。 And second, your implementation is incorrect. 其次,您的实现不正确。 Try to run it on 18 (largest prime is 3) and see that it returns
9
which is obviously not prime. 尝试在18(最大质数为3)上运行它,并查看返回的
9
显然不是质数。
As for the stackoverflow, since there's no condition that restrict n > 1
in some cases the calculation will continue with -1, -2, -3,...
until you'll get stackoverflow... 至于stackoverflow,由于在某些情况下没有限制
n > 1
条件,计算将继续为-1, -2, -3,...
直到得到stackoverflow...。
And last, the JVM does not support tail-recursion optimization, but even if it did - you'll almost always be better with an iterative solution because unlike recursive solutions - it doesn't open a new frame on the stack for every recursive call (because there are no recursive calls - it runs in a loop). 而在去年,该JVM 不支持尾递归优化,但即使做了-你几乎永远是更好地与迭代求解,因为不像递归解决方案-它不会打开堆栈上一个新的框架,每递归调用(因为没有递归调用-它在循环中运行)。
Edit 编辑
n/2
and go down (minus one each iteration). n/2
开始然后向下(每次迭代减一)。 p
is: p > 1
and p
can be divided only by itself (and 1
). p
的定义是: p > 1
并且p
只能除以自身(和1
)。 Use this definition and write an iterative method boolean isPrime(int num)
boolean isPrime(int num)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.