In this tutorial, you shall learn how to write a program to check if given number is in Fibonacci series in Kotlin.
Kotlin – Check if number is part of Fibonacci Series
To check if given number is in Fibonacci series in Kotlin, we have to generate the Fibonacci series as long as the the last number in the series is not less than the given number. And then you can check if the last number in the generated series equals the given number. If so, then the given number is a part of Fibonacci series, else not.
Program
In the following program, we read a number from user and store it in num
, then check if this number is a part of Fibonacci series.
We write a function isFibonacci()
that takes a number as argument, and returns a boolean value of true if the number is part of the series, or false otherwise.
Main.kt
fun isFibonacci(number: Int): Boolean {
var a = 0
var b = 1
var fib = 0
while (fib < number) {
fib = a + b
a = b
b = fib
}
return fib == number || number == 0
}
fun main() {
print("Enter an integer : ")
val num = readLine()!!.toInt()
if (isFibonacci(num)) {
println("$num is part of the Fibonacci series.")
} else {
println("$num is not part of the Fibonacci series.")
}
}
Output #1
Enter an integer : 8
8 is part of the Fibonacci series.
Output #2
Enter an integer : 10
10 is not part of the Fibonacci series.
Related tutorials for the above program
Conclusion
In this Kotlin Tutorial, we learned how to check if given number is a part of Fibonacci series.