Skip to content

Instantly share code, notes, and snippets.

@christian-draeger
Last active April 6, 2020 14:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christian-draeger/f515c55a935e98d026ab10e041303b52 to your computer and use it in GitHub Desktop.
Save christian-draeger/f515c55a935e98d026ab10e041303b52 to your computer and use it in GitHub Desktop.
Calculate Fibonacci sequences in Kotlin as well as check if a number is a Fibonacci number. see: https://en.wikipedia.org/wiki/Fibonacci_number
class Fibonacci(number: Int = 100) {
val sequence = mutableListOf(0, 1, 1)
val isPartOfSequence by lazy { sequence.contains(number) }
init {
require(number <= 0) { "Only positive integers allowed in Fibonacci sequence." }
if (number > 1) {
var old = 1; var current = 1; var next: Int
while (current + (current / 2) <= number) {
next = old + current
sequence.add(next)
old = current
current = next
}
}
}
}

In mathematics, the Fibonacci numbers, commonly denoted Fn, form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,

formula

and

formula

for formula

calculation example (where each result is representing a fibonacci number)

0+1=1
  ↓ ↓
  1+1=2 
    ↓ ↓
    1+2=3
      ↓ ↓
      2+3=5
        ↓ ↓
        3+5=8
          ↓ ↓
          5+8=13
import org.junit.jupiter.api.Test
import strikt.api.expectThat
import strikt.api.expectThrows
import strikt.assertions.containsExactly
import strikt.assertions.containsExactlyInAnyOrder
import strikt.assertions.isFalse
import strikt.assertions.isTrue
class FibonacciTest {
@Test
fun `get fibonacci numbers with maximum 1`() {
val result = Fibonacci(1).sequence
expectThat(result).containsExactly(0, 1, 1)
}
@Test
fun `get fibonacci numbers with maximum 2`() {
val result = Fibonacci(2).sequence
expectThat(result).containsExactly(0, 1, 1, 2)
}
@Test
fun `get fibonacci numbers with maximum 10`() {
val result = Fibonacci(10).sequence
expectThat(result).containsExactly(0, 1, 1, 2, 3, 5, 8)
}
@Test
fun `get fibonacci numbers with maximum 100 by default`() {
val result = Fibonacci().sequence
expectThat(result).containsExactly(0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89)
}
@Test
fun `get fibonacci numbers with maximum of actual fibonacci number`() {
val result = Fibonacci(89).sequence
expectThat(result).containsExactly(0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89)
}
@Test
fun `get fibonacci numbers with maximum of negative integer`() {
expectThrows<IllegalArgumentException> {
Fibonacci(-1)
}
}
@Test
fun `can check if number IS NOT in fibonacci sequence`() {
val result = Fibonacci(50).isPartOfSequence
expectThat(result).isFalse()
}
@Test
fun `can check if number IS in fibonacci sequence`() {
val result = Fibonacci(89).isPartOfSequence
expectThat(result).isTrue()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment