Golang : Test if an input is an Armstrong number example
An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself.
For example, 371 is an Armstrong number since 3**3 + 7**3 + 1**3 = 371.
Below is an example code to test if a given input is an Armstrong number or not.
package main
import (
"fmt"
)
func main() {
var rightMost, num int
var cubicSum int = 0
var tempNum int = 0
fmt.Print("Enter a 3 digits number : ")
fmt.Scanf("%d", &num)
tempNum = num
// get the right most digit
for {
rightMost = tempNum % 10
cubicSum += rightMost * rightMost * rightMost
// update the input digit minus the processed rightMost
tempNum /= 10
if tempNum == 0 {
// break the for loop
break
}
}
if num == cubicSum {
fmt.Println(num, "is an Armstrong number!")
} else {
fmt.Println(num, "is NOT an Armstrong number!")
}
}
Sample output:
$ go run armstrong.go
Enter a 3 digits number : 371
371 is an Armstrong number!
$ go run armstrong.go
Enter a 3 digits number : 157
157 is NOT an Armstrong number!
$ go run armstrong.go
Enter a 3 digits number : 153
153 is an Armstrong number!
References:
http://pages.mtu.edu/~shene/COURSES/cs201/NOTES/chap04/arms.html
See also : Golang : Test a slice of integers for odd and even numbers
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+2.5k Golang : Build new URL for named or registered route with Gorilla webtoolkit example
+13.1k SSL : How to check if current certificate is sha1 or sha2
+2.9k Golang : How to calculate the distance between two coordinates using Haversine formula
+2.6k Golang : Handling image beyond OpenCV video capture boundary
+3.2k Golang : Squaring elements in array
+5.8k Golang : Get absolute path to binary for os.Exec function with exec.LookPath
+41.5k Golang : Upload file from web browser to server
+4.7k Golang : Extract part of string with regular expression
+3.7k Findstr command the Grep equivalent for Windows
+3.8k Golang : Use regular expression to get all upper case or lower case characters example
+2.4k Clean up Visual Studio For Mac installation failed disk full problem
+18.7k Golang : How to write CSV data to file