Skip to main content

How to check if a number is a Fibonacci number in Kotlin

How to check if a number is a Fibonacci number in Kotlin.

Here's a detailed step-by-step tutorial on how to check if a number is a Fibonacci number in Kotlin:

Step 1: Understand the Fibonacci sequence

  • The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones.
  • The sequence starts with 0 and 1, so the first few numbers in the sequence are: 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on.

Step 2: Define a function to check if a number is a perfect square

  • In order to determine if a number is a Fibonacci number, we need to check if it is a perfect square.
  • Create a function called isPerfectSquare that takes an integer as a parameter and returns a boolean value indicating if the number is a perfect square.
  • To check if a number is a perfect square, we can take the square root of the number and check if the square of the square root is equal to the original number.
  • Here's an example implementation of the isPerfectSquare function:
fun isPerfectSquare(number: Int): Boolean {
val squareRoot = Math.sqrt(number.toDouble()).toInt()
return squareRoot * squareRoot == number
}

Step 3: Check if a number is a Fibonacci number

  • Create a function called isFibonacciNumber that takes an integer as a parameter and returns a boolean value indicating if the number is a Fibonacci number.
  • To check if a number is a Fibonacci number, we need to check if either (5 number number + 4) or (5 number number - 4) is a perfect square.
  • If either of these expressions is a perfect square, then the number is a Fibonacci number.
  • Here's an example implementation of the isFibonacciNumber function:
fun isFibonacciNumber(number: Int): Boolean {
return isPerfectSquare(5 * number * number + 4) || isPerfectSquare(5 * number * number - 4)
}

Step 4: Test the functions

  • You can now test the isFibonacciNumber function to check if a number is a Fibonacci number.
  • Here are some example test cases:
fun main() {
val numbers = listOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)

for (number in numbers) {
if (isFibonacciNumber(number)) {
println("$number is a Fibonacci number")
} else {
println("$number is not a Fibonacci number")
}
}
}
  • When you run the above code, it should output the following:
0 is a Fibonacci number
1 is a Fibonacci number
2 is a Fibonacci number
3 is a Fibonacci number
4 is not a Fibonacci number
5 is a Fibonacci number
6 is not a Fibonacci number
7 is not a Fibonacci number
8 is a Fibonacci number
9 is not a Fibonacci number
10 is not a Fibonacci number
11 is not a Fibonacci number
12 is not a Fibonacci number
13 is a Fibonacci number
14 is not a Fibonacci number
15 is not a Fibonacci number

That's it! You now have a step-by-step tutorial on how to check if a number is a Fibonacci number in Kotlin.