1

Im trying to create a function that determines if a number is a fibonacci number or not in Scala. Can someone look at my code and let me know what I'm missing? Thanks

def isFibNumber(n: Int): Boolean = {

  var fib1 = 0;
  var  fib2 = 1;
do {
    var saveFib1 = fib1;
    fib1 = fib2;
    fib2 = saveFib1 + fib2;
    }
while (fib2 < n);

if (fib2 == n)
    return true;
else
    return false;
}
abpre
  • 57
  • 7

2 Answers2

2
def isFibonacciNumber(n: Int): Boolean = {
  var fib1 = -1;
  var  fib2 = 1;
  var res = 0;

do {
    res = fib1+fib2;
    fib1 = fib2;
    fib2 = res;
} while (res < n);

if (res == n)
    return true;
else
    return false;
}

This should work. You had error in your algorithm.

Sibidharan
  • 2,717
  • 2
  • 26
  • 54
  • Did you test your code? it doesnt seem to be working. Also as part of the requeriment of this task I need to use def isFibNumber(n: Int): Boolean = { and not def firstNFibonacciNumbers(n: Int): Stream[Int] = { – abpre Feb 04 '16 at 04:03
  • @abpre can u be more presice? So I can help you. – Sibidharan Feb 08 '16 at 07:20
2

That would help. No loop required

http://www.geeksforgeeks.org/check-number-fibonacci-number/

object Fib {


  def isPerfectSq(n: Int): Boolean = {
    val res = math.round(math.sqrt(n))
    res * res == n.toLong
  }

  def isFibonacci(n: Int) = {
    isPerfectSq(5 * n * n - 4) || isPerfectSq(5 * n * n + 4)
  }


}
jdevelop
  • 12,176
  • 10
  • 56
  • 112