Unique prime factors using HashSet
Posted
by
theGreenCabbage
on Stack Overflow
See other posts from Stack Overflow
or by theGreenCabbage
Published on 2014-05-26T21:23:08Z
Indexed on
2014/05/26
21:25 UTC
Read the original article
Hit count: 265
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
.
© Stack Overflow or respective owner