You are using recursion, which means that a function will call itself.
So, if we trace what your function calls are when you call return
, we will have something like that:
IntegerFactorise.main()
|-> IntegerFactorise.findPrimeFactors(2639)
|-> IntegerFactorise.findPrimeFactors(377)
|-> IntegerFactorise.findPrimeFactors(29) -> return true;
So, when you return in the last findPrimeFactors()
, you will only return from this call, not from all the stack of calls, and the execution of the previous findPrimeFactors()
will continue just after the point where you called findPrimeFactors()
.
If you want to return from all the stack of calls, you have to modify your code to do something like that:
else if(isPrimeNumber(i) && num % i == 0) {
primeFactors.add(i);
return findPrimeFactors(num / i);
}
So that when the last findPrimeFactors()
returns, all the previous findPrimeFactors()
which called it will return too.