display all prime factors of a number
guys, calculating whether a number is prime or not is pretty straight forward
Code :
static boolean isPrime(int p)
{
for(int i = 2; i < p; i++)
{
if(p % i == 0) return false;
}
return true;
}
given the fact that I have a code that tells me whether a number is prime or not, how could I implement another method that display all prime factors of a number
Thanks
Re: display all prime factors of a number
Well, how do you know if a number is a factor of another number (your prime code gives a pretty good hint)?
So, for every factor of a given number, just call your isPrime(int) method and send it the factor. If the method returns true, you know the factor is a prime (and then continue to check the rest of the factors).
Re: display all prime factors of a number
Thanks... once you explained it like that I was able to see it right away. But now I have a small problem with my code. For example, lets take the number 20.
my code displays
20 = 2, 5
which are both prime factors of 20, but I'm not sure if the correct way of displaying is 2, 5 or 2 * 2 * 5, or 2^2 * 5. the first way I think is right as my question ask for all prime factors of the number, and since 2 is repeated twice. But lets say that I would like to display 2^2 * 5 or 2 * 2 * 5. How could I approach the problem then?
Thanks
Re: display all prime factors of a number
Once you have found that 2 is a prime factor you could check higher and higher powers of 2 to find the highest power that is a factor.
Re: display all prime factors of a number
20/2 = 10;
10/2 = 5;
5/2 = 2.5
20%2 = 0;
10% 2 = 0;
5%2 = 1;
20/5 = 4;
20%5 = 0;
4%5 = 4;
4/5 = .8
4/2 = 2
4%2 = 0;
2/2 = 1
2%2 = 0;
12
12/2 = 6;
6/2 = 3;
3/3 = 1;
2,3
9216
9216/2 = 4608
4608 /2 = 2304
2304/2 = 1152
1152/2 = 576
576/ 2 = 288
288/2 = 144
144/2 = 72
62/ 2 = 36
36/2 = 18
18/2 = 9;
9/2 = 4.5
9/3 = 3;
3/3 = 1;
1/3 = 0.33333
2^10 * 3 ^2
I have an idea for the implementation, though it's probably inefficient.
I'm working on it right now though.
It was basically to store all your prime factors in an ArrayList, then go through and divide them like above and have some kind of temporary variable inside a loop and increment it every time you can divide by that factor until you can't anymore. After that, put that factor into a HashMap and continue the same way with other factors, and then at the end, you'll have a HashMap with all of your factors, with the number as the key and the exponent as the value.
So you're hash map for 9216 would be
[2,10] [3,2]
or something like that.
That's the best I can think of. There might be, or probably is, a better and more efficient way.
Re: display all prime factors of a number
ups... post before reading last thread.