Reputation: 33
I'm working on a prime factorization program in Java one that displays all prime factors of a number even if they are repeated. And I have this:
public static void factors(int a)
{
int c=1;
for(int i = 1; i <= a;i++)
{
if(a%i == 0)
{
for(int k = 2; k < i; k++)
{
if(i%k == 0)
{
c = 1;
break;
}
else
{
c = 0;
}
}
if(c == 0 || i == 2)
{
System.out.print(i+ ", ");
}
}
}
}
I need to account for repeated factors (as in 2, 2, 2 for 8). How could I do that without completely restructuring?
Upvotes: 0
Views: 2155
Reputation: 178531
(1) if(c == 0 || i == 2)
is wrong, it will print 2
for a == 5
as well.
(2) In order to do what you are asking without changing the code (*) - you should count how many times each prime factor is diviseable by the number. It can be done by simply adding a new loop before your print statement [pseudo code]:
boolean b = true;
int k = 1;
while (b) {
if (a % (int) Math.pow(i, k+1) == 0) k++;
else b = false;
}
at the end of this loop, k denotes how many times i
is a prime factor of a
.
(*) Note: Though this approach should work, I'd still go with @KerrekSB suggestion to a redesign.
Upvotes: 0
Reputation: 727107
I think you should start over, and build an algorithm from this simple description:
List<Integer>
of prime numbers that are less than or equal to 2^161
.Finding a list of primes is a fun problem in itself. Dijkstra wrote a fascinating chapter on it back in 1972. This article has a C++ implementation and a very nice discussion.
Upvotes: 1
Reputation: 1121
You can have another collection that maintains the factors and their count and can finally account for repeated factors. A map with counts would be my choice.
Upvotes: 0