Okay, so, it dawned on me that using the time returned from a test was really stupid.
Using an actual method timer, my new method takes 0.047776 ms.
(Btw, I’m doing this in Kotlin)
fun largestPrimeFactorOf(number: Long): Long {
if(isPrimeNumber(number))return number
var i = 3
while(number % i != 0L)i+=2
return largestPrimeFactorOf(number/i)
}
fun isPrimeNumber(n: Long): Boolean {
if(n == 2L)return true
if (n % 2 == 0L || n == 1L) return false
var i = 3
while (i * i <= n) {
if (n % i == 0L)return false
i += 2
if(i % 3 == 0)i+=2
}
return true
}
The isPrimeNumber function looks slightly convoluted. Originally I had:
fun isPrimeNumber(n: Long): Boolean {
if(n == 2L)return true
if (n % 2 == 0L || n == 1L) return false
var i = 3
while (i * i <= n) {
if (n % i == 0L)return false
i += 2
}
return true
}
And that worked reasonably well, but the very first pass around, I eliminate the possibility that the number is divisible by three, because that’s the first value of i. So, in order to shave off a few checks, I added in a check to see if i (after it was increased by two) was now a multiple of three, and if it was, add two to i and effectively skip that iteration.
I thought about using a very simple sieve, but that actually wound up slowing this down. Maybe it would help if the number was really really large.