Menu
Coddy logo textTech

Adding The Twist

Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 66 of 93.

challenge icon

Challenge

Medium

In the previous lesson, you made the upper limit dynamic by reading it from input. Now, add the twist by making the divisors customizable too!

Modify your code to:

  1. Read three integers from input:
    • n - the upper limit
    • fizzDivisor - the divisor for "Fizz"
    • buzzDivisor - the divisor for "Buzz"
  2. Update your fizzBuzz function to accept three parameters: the number to check, the fizz divisor, and the buzz divisor
  3. Loop from 1 to n and print the result for each number using the custom divisors

Updated function signature:

fun fizzBuzz(num: Int, fizzDiv: Int, buzzDiv: Int): String

Return logic (same as before, but with custom divisors):

  • "FizzBuzz" if divisible by both divisors
  • "Fizz" if divisible by fizzDiv only
  • "Buzz" if divisible by buzzDiv only
  • The number as a string otherwise

Input: Three integers on separate lines - the upper limit, fizz divisor, and buzz divisor

Output: The customized FizzBuzz result for each number from 1 to n, each on its own line

Input constraints: Both divisors are positive integers. The count is between 1 and 100.

Try it yourself

fun fizzBuzz(n: Int): String {
    return if (n % 3 == 0 && n % 5 == 0) {
        "FizzBuzz"
    } else if (n % 3 == 0) {
        "Fizz"
    } else if (n % 5 == 0) {
        "Buzz"
    } else {
        n.toString()
    }
}

fun main() {
    val n = readLine()!!.toInt()
    for (i in 1..n) {
        println(fizzBuzz(i))
    }
}

All lessons in Fundamentals

Practice on your own: Kotlin playground