Project Euler #3
A colleague of mine has suggested solving Project Euler #3 as a challenge. I noticed that his code was working fine but very inefficient. In fact the specification of this task is misleading because it suggests that it is necessary to check if a solution is prime. But it is possible to formulate the solution without checking for primality. Here is my implementation in Kotlin. fun euler3(n: Long, i: Long = 2): Long = if (i >= n) n else if (n % i == 0L) euler3(n / i, i) else euler3(n, i + 1) fun main(args: Array<String>) { var numcur = euler3(600851475143) print("$numcur") } The trick is to quit the loop when i exceeds n.