Home
Scala
Odd and Even Numbers
This page was last reviewed on Dec 13, 2023.
Dot Net Perls
Odd, even. How do we compute the parity of numbers—whether they are even or odd? With Scala 3.3 we use modulo division to see if 2 divides a number evenly (with no remainder).
With def, we define two small functions that return Booleans. With isEven we return true if a number is evenly divisible by 2. And with isOdd we do the opposite.
Example methods. Let us begin. With isEven we use a short syntax form in Scala to return whether the modulo division of a number by 2 equals 0. With isOdd we simply return "not isEven."
Next We invoke this method to get a short list of numbers to test. We test each Int for even and odd status.
object Program { // These functions test for even and odd numbers. def isEven(number: Int) = number % 2 == 0 def isOdd(number: Int) = !isEven(number) def main(args: Array[String]): Unit = { // Generate a range of numbers to test. val tests = List.range(-2, 10) // Loop over numbers and indicate whether they are even or odd. for (n <- tests) { print(n) if (isEven(n)) { println(" -> Even") } if (isOdd(n)) { println(" -> Odd") } } } }
-2 -> Even -1 -> Odd 0 -> Even 1 -> Odd 2 -> Even 3 -> Odd 4 -> Even 5 -> Odd 6 -> Even 7 -> Odd 8 -> Even 9 -> Odd
Filter, generate sequences. Let us add some complexity. We repeat our isEven and isOdd numbers. We use Seq.range and then filter() to generate sequences of even and odd numbers.
Info We use filterNot with isEven to generate odd numbers—this is another way of generating odds.
object Program { // Tests parity of numbers. def isEven(number: Int) = number % 2 == 0 def isOdd(number: Int) = !isEven(number) def main(args: Array[String]): Unit = { // Generate even numbers. println("Filter even") val evens = Seq.range(0, 10).filter(isEven(_)) println(evens) // Generate odd numbers. println("Filter odd") val odds = Seq.range(0, 10).filter(isOdd(_)) println(odds) // Another way to get odd numbers. println("Filter not even") val odds2 = Seq.range(0, 10).filterNot(isEven(_)) println(odds2) } }
Filter even Vector(0, 2, 4, 6, 8) Filter odd Vector(1, 3, 5, 7, 9) Filter not even Vector(1, 3, 5, 7, 9)
Review. Testing a number's parity is simple. And with methods like filter and filterNot we can generate ranges of numbers based on their parity.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 13, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.