# Groovy web console

 Subscribeto thissite
 Tweetthisscript

## Prime Factorization

Published 9 months ago by S.J.M with tags Primes Factors Math
```//  Find all PRIME factors of a number n
//  SJM

// change n as desired:
def n = 800

def isPrime(int num) {
prime = true
for (j in 2..<num) {
if (num % j == 0)  prime = false
}
return prime
}

def listOfPrimeFactors(Integer n, List primeFactors) {

if (isPrime(n)) {
if (primeFactors.size() == 0) {
// if n is originally prime, then the factors are 1 and itself
primeFactors << 1
}
primeFactors << n
return primeFactors
}

def firstPrimeFactor = 1

for (i in 2..<n) {
if (n % i == 0) {
if (isPrime(i)) {
firstPrimeFactor = i
break
}
}
}

//  append the first prime factor to the list, divide n by that number, and repeat!
primeFactors << firstPrimeFactor
n /= firstPrimeFactor
return listOfPrimeFactors(n, primeFactors)
}

def primeFactorsOfN = listOfPrimeFactors(n, [])
println(primeFactorsOfN)

//for (j in 0..<primeFactorsOfN.size()) { println(primeFactorsOfN[j]) }  // alternate way of viewing the factors
```