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. 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 &&. 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.
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...
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).
Edit
n/2 and go down
(minus one each iteration).p is: p > 1 and p can be divided only by itself (and 1). Use this definition and write an iterative method boolean isPrime(int num)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With