Scala

Scala Odd and Even Numbers2 min read

Use modulo division to test for even and odd numbers. Call filter to generate sequences of even and odd values.Odd, even. 1 is odd. 2 is even. We all know this, but how do we compute this? With Scala 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.”

List.range: We invoke this method to get a short list of numbers to test. We test each Int for even and odd status.




Output:

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.

FilterNot: We use filterNot with isEven to generate odd numbers—this is another way of generating odds.

Output:

Leave a Comment