I need to make the following code more efficient. It takes a bit too long to run.
def aFib(n: Int): BigInt = {
var nn: Int = n
var sign: Int = 0
if (nn < 0) {
nn = -nn
sign = 2 * (nn % 2) - 1
} else {
sign = 1
}
var a: BigInt = 1
var b: BigInt = 0
var p: BigInt = 0
var q: BigInt = 1
while (nn != 0) {
if (nn % 2 == 1) {
var t = (b + a) * q + a * p
b = b * p + a * q
a = t
}
var t = p * p + q * q
q =(2 * p * q) + q * q
p = t
nn /= 2
}
sign * b
}
I've already played around with different approaches (iterative, recursive, etc.) and settled on the algorithm embodied in the code. Cognoscenti will recognise it as a well-known way to calculate positive and negative fibonacci numbers. I've written the code myself and put in BigInt. There does not appear to be a fast implementation readily available. Since Scala is a complex language and I have limited experience, my gut-feeling is that there are ways to make the code better - reducing the elapsed time. All suggestions are welcome.