I am trying to write a recursive function in Scala that takes a positive integer and prints out its prime factors. For example, 200 = 2, 2, 2, 5, 5. This is the code I have written.
println(calculatePrimeFactors(200,2))
def isPrime( x:Int ):Boolean = {
def recIsP( n:Int, i:Int ) : Boolean = (i == n) || (n % i != 0) && recIsP(n, i + 1)
recIsP(x,2)
}
def calculatePrimeFactors(n:Int,i:Int):String= {
if (i==n) {
""
}else if(isPrime(i) && n%i==0){
i.toString + ", " + calculatePrimeFactors(n,i+1)
}else{
calculatePrimeFactors(n,i+1)
}
}
My code outputs 2,5, .
How can I make this so that the code works correctly and outputs 2,2,2,5,5,. I tried using a loop with this statement n = n / i, but Scala returns an error saying that reassignment to val can't be done.