From 1b0d25c9769c0a02b233701234148373bef54613 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pau=20L=C3=B3pez=20N=C3=BA=C3=B1ez?= Date: Fri, 3 Oct 2025 04:10:43 +0200 Subject: [PATCH] Add ModularExponentiation function to math directory This PR adds a function to compute (base^exponent) % mod efficiently in Kotlin using iterative binary exponentiation. The function handles large exponents without overflow issues. Example usage is included in the main() function. --- src/main/kotlin/ModularExponentiation.kt | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 src/main/kotlin/ModularExponentiation.kt diff --git a/src/main/kotlin/ModularExponentiation.kt b/src/main/kotlin/ModularExponentiation.kt new file mode 100644 index 0000000..41854ce --- /dev/null +++ b/src/main/kotlin/ModularExponentiation.kt @@ -0,0 +1,19 @@ +fun modularExponentiation(base: Long, exponent: Long, mod: Long): Long { + var result = 1L + var b = base % mod + var e = exponent + while (e > 0) { + if (e % 2 == 1L) { + result = (result * b) % mod + } + b = (b * b) % mod + e /= 2 + } + return result +} + +// Test main function +fun main() { + println("3^13 % 7 = ${modularExponentiation(3, 13, 7)}") // Output: 3 + println("5^117 % 19 = ${modularExponentiation(5, 117, 19)}") // Output: 1 +}