Unique prime factors using HashSet
- by theGreenCabbage
I wrote a method that recursively finds prime factors. Originally, the method simply printed values. I am currently trying to add them to a HashSet to find the unique prime factors.
In each of my original print statements, I added a primes.add() in order to add that particular integer into my set.
My printed output remains the same, for example, if I put in the integer 24, I get 2*2*2*3. However, as soon as I print the HashSet, the output is simply [2].
public static Set<Integer> primeFactors(int n)
{
Set<Integer> primes = new HashSet<Integer>();
if(n <= 1)
{
System.out.print(n);
primes.add(n);
}
else
{
for(int factor = 2; factor <= n; factor++)
{
if(n % factor == 0)
{
System.out.print(factor);
primes.add(factor);
if(factor < n)
{
System.out.print('*');
primeFactors(n/factor);
}
return primes;
}
}
}
return primes;
}
I have tried debugging via putting print statements around every line, but was unable to figure out why my .add() was not adding some values into my HashSet.