Given a positive integer N, the task is to check whether the given number N is Even or Odd.
Examples:
Input : N = 10 Output : Even Input : N = 5 Output : Odd
Method 1:
An even number is an integer which is “evenly divisible” by 2. This means that if the integer is divided by 2, it yields no remainder or 0 as remainder. Similarly, an Odd number is an integer which is not “evenly divisible” by 2 and will leaves 1 as remainder.
Below is the implementation of above approach:
// Scala program to check
// whether the given number
// is Even or Odd
// Creating Object
object W3Colleges {
// Function to check
// whether the given number
// is Even or Odd
def isEvenOrOdd(N: Int): String = {
if (N % 2 == 0)
"Even"
else
"Odd"
}
// Driver Code
def main(args: Array[String]): Unit = {
val N = 10
println(s"The number $N is ${isEvenOrOdd(N)}.")
}
}
Output:
Even
Method 2: Using Bit Manipulation
This method is based on the fact that a number is Odd if Bit-wise AND (&) of the number with 1 is 1 and Even if 0.
Below is the implementation of above approach:
// Scala program to check
// whether the given number
// is Even or Odd
// Creating Object
object W3Colleges {
// Function to check
// whether the given number
// is Even or Odd through
// Bitwise AND operation
def isEvenOrOdd(N: Int): String = {
if ((N & 1) == 1)
"Odd"
else
"Even"
}
// Driver Code
def main(args: Array[String]): Unit = {
val N = 10
println(s"The number $N is ${isEvenOrOdd(N)}.")
}
}
Output:
Even
