Results 1 to 4 of 4
Thread: Finding Prime Factors
 04092011, 02:35 AM #1Member
 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;
}
 04092011, 02:38 AM #2
 Join Date
 Jan 2011
 Location
 Richmond, Virginia
 Posts
 3,069
 Blog Entries
 3
 Rep Power
 11
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

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 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; }
 04092011, 01:14 PM #4
 Join Date
 Sep 2008
 Location
 Voorschoten, the Netherlands
 Posts
 14,394
 Blog Entries
 7
 Rep Power
 25
Similar Threads

Finding Largest Prime Factor
By perito in forum New To JavaReplies: 7Last Post: 11082010, 09:25 PM 
Finding nth prime number
By dextr in forum New To JavaReplies: 2Last Post: 04122010, 11:42 PM 
Prime Number  System print all the prime numbers ...
By pinkdreammsss in forum New To JavaReplies: 20Last Post: 04262009, 01:50 AM 
Prime numbers
By tercius in forum New To JavaReplies: 3Last Post: 05042008, 06:05 AM 
Prime numbers
By gapper in forum New To JavaReplies: 3Last Post: 02072008, 11:09 AM
Bookmarks