1. Member
Join Date
Mar 2011
Posts
9
Rep Power
0

## 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;
}

2. 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
Java 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.

3. you'll need a loop to run from the number to 1 and add a list of prime numbers like this:

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

4. 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:

Java Code:
```public java.util.List<Integer> getPrimeNumbers(int randomNumber) {
//declare list
//loop backwards
for (int i=randomNumber; i>0; i--) {
boolean iIsPrime = randomNumber%i == 0;
if (iIsPrime) {
}
}
//return result
}```
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

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•