https://kotlinlang.org logo
#codereview
Title
# codereview
i

ianbrandt

06/25/2018, 3:25 AM
Been practicing with Uncle Bob's Prime Factors kata (http://butunclebob.com/ArticleS.UncleBob.ThePrimeFactorsKata). Any improvements here, given the absence of C-style
for
loops in Kotlin? Perhaps a functional approach?
Copy code
fun primeFactorsOf(integer: Int): List<Int> {
	val primeFactors = mutableListOf<Int>()
	var n = integer
	var divisor = 2
	while (n > 1) {
		while (n % divisor == 0) {
			primeFactors.add(divisor)
			n /= divisor
		}
		divisor++
	}
	return primeFactors
}
For comparison, a Java implementation with C-style loops:
Copy code
public static List<Integer> primeFactorsOf(int integer) {
	List<Integer> primeFactors = new ArrayList<>();
	for (int divisor = 2; integer > 1; divisor++)
		for (; integer % divisor == 0; integer /= divisor)
			primeFactors.add(divisor);
	return primeFactors;
}
g

gildor

06/25/2018, 5:06 AM
I'm really prefer version with
while
for much-much better readability and simplicity And It’s good example why C-style
for
is dropped 🙈
2
👍 1
d

dalexander

06/25/2018, 1:11 PM
Here's a tail recursive implementation as another option. Someone might be able to do this better than I though, since I'm mostly unfamiliar with the patterns. I also engage in a little unnecessary code golf with the pair construction for the result of the if statement.
Copy code
tailrec fun primeFactorization(number: Int, divisor: Int = 2, res: MutableList<Int> = mutableListOf()): List<Int> {
    if(number <= 1) {
        return res
    }

    val (nextNumber, nextDivisor) = if(number % divisor == 0) {
        res.add(divisor)
        (number / divisor) to divisor
    } else {
        number to (divisor + 1)
    }

    return primeFactorization(nextNumber, nextDivisor, res)
}
👍 1
3 Views