Professor Java # Prime Factorizer Calculator

Number:

Factorization:

## primeFactorization

public static String primeFactorization(long num){ //method signature. takes long, returns string of factorization
for(int i=2;i<=num;i++){ //loops from 2 to the num
if(num%i==0){ //checks if i is a divisor of num
ans+=i+"*"; //writes i in prime factorization
num=num/i; //since it is written down, num=num/i
i--; //just in case their are multiple factors of same number. For example, 12=2*2*3
}
}
return(ans.substring(0,ans.length()-1)); //takes away last asterisk. Factorization of 4=2*2*=>2*2
}

One of my favorite self-made functions. Simple, yet elegant. Takes a long num and returns the factorization of the form for example 24=2*2*2*3. Comments are pretty much self explanatory, Loops through 2->num checking if it is a divisor, if it is, it is put into the answer. num=num/i prevents same factors that are already accounted for, and i-- for repeated factors, like 4=2*2. There is an extra asterisk at the end, so we take away the last one using substring. Note: because of how the program is constructed, all numbers in the factorization are prime, and in increasing order. See above for Javascript implementation. Note that if the number returned is the same as the number entered, then it is prime. Provided by website-hit-counters.com site. 