0 Replies - 324 Views - Last Post: 03 March 2011 - 08:50 AM

#1 TFoSSDQ   User is offline

  • D.I.C Regular
  • member icon

Reputation: 123
  • View blog
  • Posts: 253
  • Joined: 09-December 10

Return prime factors as an int array iteratively

Posted 03 March 2011 - 08:50 AM

Description: Just keep the methods together.It takes an int parameter to return the prime factors of as an int array.
public static int[] getPrimeFacts(int num)
{
    int temp = num; //will hold the num to get factors of
    int temp2 = 2; //will hold each prime number that will be tested
    String facts = ""; //will hold the known prime factors separated by spaces

    while(!isPrime(temp)) //while temp is not prime
    {
    	if(temp % temp2 == 0) //if temp divides temp2 (a prime) evenly
    	{
    		facts += temp2+" "; //add temp2 to facts
    		temp /= temp2; //divide temp2 out of temp;
   		temp2 = 1; //reset temp2 to recycle through the primes
    	}
    	temp2 = nextPrime(temp2); //calls nextPrime to get the next prime after the argument
    }

    facts += temp; //temp is prime meaning its remaining self is also a factor

    String[] strArr = facts.split(" "); //split up facts into a String array
    int[] intArr = new int[strArr.length]; //initialize our int array which will hold the numbers the same length as the String array

    for(int i = 0; i < strArr.length; i++)
    {
    	intArr[i] = Integer.parseInt(strArr[i]); //parse the numbers into our int array
    }

    return intArr; //return the int array which now holds all prime factors of the inputted num
}

public static int nextPrime(int num) //returns the next prime number after the argument
{
    if(num > 1)
    {
	int temp = num+1; //we're going to start with the next number after num
        while(!isPrime(temp)) //while temp is not prime
            temp++; //move on and check the next number
	return temp; //temp is now prime and we return it
    } 
    else 
    {
	return 2; //2 will be the first prime for our situation
    }
}

public static boolean isPrime(int num) //determines is a number is prime
{
    int temp = 2; //checking number
    while(temp <= (int) Math.floor(Math.sqrt(num))) //while the checking number < the floored sqrt of num (any higher would be pointless)
    {
    	if(num % temp == 0) //if it divides evenly
    	{
    		return false; //then num is not prime
    	}
    	temp++; //increment the checking number
    }
    return true; //return true if temp never divided evenly, meaning num is prime
}


Is This A Good Question/Topic? 0
  • +

Page 1 of 1