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
+13.7k Facebook PHP getUser() returns 0
+12.3k Golang : convert(cast) string to integer value
+16.2k Golang : How to reverse elements order in map ?
+7.9k Golang : Command line ticker to show work in progress
+21.1k Golang : Convert PNG transparent background image to JPG or JPEG image
+17k Golang : read gzipped http response
+7.7k Golang : Detect sample rate, channels or latency with PortAudio
+10.7k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+23.1k Golang : Test file read write permission example
+6.9k Golang : Find the longest line of text example
+20.4k Golang : How to get struct tag and use field name to retrieve data?
+7.7k Golang : Rot13 and Rot5 algorithms example