Skip to content
22 changes: 22 additions & 0 deletions src/main/kotlin/math/Fibonacci.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/**
* Returns the n-th Fibonacci number (0-based index) using iteration.
*/
fun fibonacci(n: Int): Long {
require(n >= 0) { "n must be non-negative" }
if (n == 0) return 0
if (n == 1) return 1
var a = 0L
var b = 1L
for (i in 2..n) {
val temp = a + b
a = b
b = temp
}
return b
}

fun main() {
println("Fibonacci(0) = ${fibonacci(0)}") // 0
println("Fibonacci(1) = ${fibonacci(1)}") // 1
println("Fibonacci(10) = ${fibonacci(10)}") // 55
}
18 changes: 18 additions & 0 deletions src/main/kotlin/math/GCD.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/**
* Computes the Greatest Common Divisor (GCD) of two integers using Euclid's algorithm.
*/
fun gcd(a: Int, b: Int): Int {
var x = a
var y = b
while (y != 0) {
val temp = y
y = x % y
x = temp
}
return kotlin.math.abs(x)
}

fun main() {
println("GCD of 12 and 18 is ${gcd(12, 18)}") // 6
println("GCD of 7 and 3 is ${gcd(7, 3)}") // 1
}
16 changes: 16 additions & 0 deletions src/main/kotlin/math/IsPrime.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/**
* Returns true if the given number is prime, false otherwise.
*/
fun isPrime(n: Int): Boolean {
if (n < 2) return false
for (i in 2..kotlin.math.sqrt(n.toDouble()).toInt()) {
if (n % i == 0) return false
}
return true
}

fun main() {
println("7 is prime? ${isPrime(7)}") // true
println("10 is prime? ${isPrime(10)}") // false
println("13 is prime? ${isPrime(13)}") // true
}
23 changes: 23 additions & 0 deletions src/main/kotlin/math/LCM.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/**
* Computes the Least Common Multiple (LCM) of two integers.
*/
fun lcm(a: Int, b: Int): Int {
return kotlin.math.abs(a * b) / gcd(a, b)
}

// Reusing gcd function from GCD.kt
fun gcd(a: Int, b: Int): Int {
var x = a
var y = b
while (y != 0) {
val temp = y
y = x % y
x = temp
}
return kotlin.math.abs(x)
}

fun main() {
println("LCM of 12 and 18 is ${lcm(12, 18)}") // 36
println("LCM of 5 and 7 is ${lcm(5, 7)}") // 35
}
17 changes: 17 additions & 0 deletions src/main/kotlin/math/nCr.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/**
* Computes the number of combinations (n choose r)
*/
fun nCr(n: Int, r: Int): Long {
require(n >= 0 && r >= 0 && r <= n) { "Invalid n or r" }
var result = 1L
for (i in 1..r) {
result = result * (n - i + 1) / i
}
return result
}

fun main() {
println("C(5,2) = ${nCr(5,2)}") // 10
println("C(10,3) = ${nCr(10,3)}") // 120
println("C(6,0) = ${nCr(6,0)}") // 1
}