Scala program to find all divisors of a number

1. Introduction

A divisor of a number is an integer that can be multiplied by another integer to produce the number. For example, the divisors of 12 are 1, 2, 3, 4, 6, and 12. In this tutorial, we will implement a Scala program to find all divisors of a given number.

2. Program Steps

1. Initialize the Scala environment.

2. Implement a method to find divisors of a number.

3. Input the desired number.

4. Call the method and print the list of divisors.

5. Execute the program.

3. Code Program

object DivisorsFinder {
  def main(args: Array[String]): Unit = {
    val number = 12

    // Get the divisors of the number
    val divisors = findDivisors(number)
    println(s"Divisors of $number are: ${divisors.mkString(", ")}")
  }

  // Method to find divisors of a number
  def findDivisors(num: Int): List[Int] = {
    (1 to num).filter(num % _ == 0).toList
  }
}

Output:

Divisors of 12 are: 1, 2, 3, 4, 6, 12

Explanation:

1. The code is encapsulated within the DivisorsFinder object.

2. In the main function, we specify our desired number with the variable number.

3. The method findDivisors is defined to find and return all divisors of the input number. This method utilizes Scala's filter function on a range from 1 to num to get all numbers that divide num without leaving a remainder.

4. In the main function, we call the findDivisors method and then print the list of divisors for the given number.

5. For our example number 12, the output displays its divisors: 1, 2, 3, 4, 6, and 12.


Comments