TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to GO

Golang Odd and Even Numbers

Use modulo division to decide whether a number is even or odd. Some sample numbers are tested.
Odd, even numbers. Some numbers are odd. Others are even. We can use modulo division to tell whether a number is divisible by two. This tells us the parity of a number.
An odd issue. To tell if a number is even, we see if it evenly divisible by 2. But to tell if it is odd, we must allow a remainder of either 1 or -1. A negative number may be odd.
Example program. This program introduces the Even and Odd funcs. We test Even() and Odd() in the main method. Both methods return a bool.

Even: We use modulo division to see if a number is evenly divisible by 2. If there is no remainder, we have an even number.

Odd: We implement Odd() in terms of Even. Every integer that is not Even is Odd.

Result: The program iterates through the numbers -4 through 4 inclusive and displays whether each one is even or not.

Golang program that test seven, odd numbers package main import "fmt" func Even(number int) bool { return number%2 == 0 } func Odd(number int) bool { // Odd should return not even. // ... We cannot check for 1 remainder. // ... That fails for negative numbers. return !Even(number) } func main() { for i := -4; i <= 4; i++ { // Test the even func. fmt.Printf("Number: %v, Even: %v", i, Even(i)) fmt.Println() } // Test the odd method. if Odd(1) { fmt.Println("ok") } } Output Number: -4, Even: true Number: -3, Even: false Number: -2, Even: true Number: -1, Even: false Number: 0, Even: true Number: 1, Even: false Number: 2, Even: true Number: 3, Even: false Number: 4, Even: true ok
Simple methods. In the math package, I found no methods that reveal the parity of numbers. So a simple method that tells us this can be useful in quick Go programs.Math: golang.org
In general, using built-in methods from the "math" package is the best choice. So it is worthwhile to check that no existing math methods are available.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf