In this article, we will learn about code and algorithm to check whether a Number is Even or Odd in go golang.
There are many ways to check whether a Number is Even or Odd in go golang which are given below:
1:)
Algorithm:
- Get the number as input from user
- Do modulus by 2 of that number
- If modulus by 2 of number is zero then it is even number otherwise odd number.
Example with Code:
package main import "fmt" func main(){ fmt.Print("Enter number : ") var n int fmt.Scanln(&n) if ( n % 2 == 0 ) { fmt.Println(n, "is Even number") }else{ fmt.Println(n, "is Odd number") } }
2:)
Algorithm:
- Get the number as input from user
- Do bitwise and operator (&) between number and 1 (eg. number & 1)
- If the result of bitwise and operator (&) between number and 1 is zero then it is even number otherwise odd number.
Example:
Number = 10
/* Do bitwise and operator (&) between 10 and 1 to get to know whether 10 is even or odd number */
10 & 1
Binary of 10 is 1010
Binary of 1 is 1
1010 & 0001 = 0 (Result is zero, So 10 is even number)
/* Do bitwise and operator (&) between 11 and 1 to get to know whether 11 is even or odd number */
Number = 11
11 & 1
Binary of 11 is 1011
Binary of 1 is 1
1011 & 0001 = 1 (Result is one, So 11 is odd number)
Code:
package main import "fmt" func main(){ fmt.Print("Enter number : ") var n int fmt.Scanln(&n) if (n & 1 == 1) { fmt.Println(n,"is Odd number") } else { fmt.Println(n,"is Even number") } }
Output:
Enter number : 13
13 is Odd number
Enter number : 10
10 is Even number
References:
https://en.wikipedia.org/wiki/Parity_(mathematics)
https://brilliant.org/wiki/even-and-odd-numbers/
To learn more about go golang, please follow given below link:
https://www.techieindoor.com/go-lang-tutorial/