# Finding Prime Factors

• 04-09-2011, 02:35 AM
Need Help
Finding Prime Factors
I need to write a program that produces a random integer between 1 and 200.

Then that number needs to be listed along with all of its prime factors.

I think I'm good with the creating of the random number. The other part of the code I think just says if the number is prime or not. I need to try to change it so it produces the prime factors. Can anyone help me write this?

public Driver()
{
// initialise instance variables
int p = (int)(Math.random()*200+1);
System.out.println(p);
}

public boolean isPrime(int p) {
int divisor;
boolean looksPrime;
looksPrime = true;
divisor = 2;
while (divisor <= Math.sqrt(p)) {
if (p/divisor == (double)p/divisor) {
looksPrime = false;
}
divisor++;
}
return looksPrime;
}
• 04-09-2011, 02:38 AM
sunde887
testing for prime you should consider using the modulus operator in that if clause. the modulus operator(%) returns the remainder of the 2 numbers being divided
Code:

```5 % 2 == 1 5 % 5 == 0```
Now, how much do you understand about finding prime factors? I consider you look up how and work a few out by hand and see if it helps you understand how to approach this problem. Then try coding it and post up what you get, with specific questions indicating what you are stuck on.
• 04-09-2011, 10:28 AM
ozzyman
you'll need a loop to run from the number to 1 and add a list of prime numbers like this:

Code:

```public java.util.List<Integer> getPrimeNumbers(int randomNumber) {     //declare list     java.util.List<Integer> primeNumbers = new java.util.ArrayList<Integer>();     //loop backwards     for (int i=randomNumber; i>0; i--) {         boolean iIsPrime = randomNumber%i == 0;         if (iIsPrime) {             primeNumbers.add(i);         }     }     //return result     return primeNumbers; }```
• 04-09-2011, 01:14 PM
JosAH
Quote:

Originally Posted by ozzyman
you'll need a loop to run from the number to 1 and add a list of prime numbers like this:

Code:

```public java.util.List<Integer> getPrimeNumbers(int randomNumber) {     //declare list     java.util.List<Integer> primeNumbers = new java.util.ArrayList<Integer>();     //loop backwards     for (int i=randomNumber; i>0; i--) {         boolean iIsPrime = randomNumber%i == 0;         if (iIsPrime) {             primeNumbers.add(i);         }     }     //return result     return primeNumbers; }```

That solution is not correct; any number n > 0 has the property that n%n == 0, so your first pass through the loop will show that n isn't prime.

kind regards,

Jos