Find Armstrong Numbers in an Interval in Go
In this tutorial, we will learn how to find all Armstrong numbers in a given interval in Go. We will cover the basic concept of Armstrong numbers and implement a function to identify Armstrong numbers within a specified range.
What is an Armstrong Number
An Armstrong number (also known as a narcissistic number) is a number that is equal to the sum of its own digits each raised to the power of the number of digits. For example, 153 is an Armstrong number because 1³ + 5³ + 3³ = 153.
Syntax
The syntax to find Armstrong numbers in an interval in Go is:
import (
"fmt"
"math"
)
func isArmstrongNumber(num int) bool {
originalNum := num
var sum int
numDigits := int(math.Log10(float64(num))) + 1
for num != 0 {
digit := num % 10
sum += int(math.Pow(float64(digit), float64(numDigits)))
num /= 10
}
return sum == originalNum
}
func findArmstrongNumbers(start, end int) []int {
var armstrongNumbers []int
for i := start; i <= end; i++ {
if isArmstrongNumber(i) {
armstrongNumbers = append(armstrongNumbers, i)
}
}
return armstrongNumbers
}
Example 1: Finding Armstrong numbers in an interval
We can create a function to check if a number is an Armstrong number and use it to find all Armstrong numbers within a specified range.
For example,
- Import the
fmt
andmath
packages. - Define a helper function named
isArmstrongNumber
that takes one parameternum
of typeint
and returns a boolean indicating ifnum
is an Armstrong number. - Define a function named
findArmstrongNumbers
that takes two parametersstart
andend
of typeint
. - Initialize an empty slice to store the Armstrong numbers.
- Use a
for
loop to iterate fromstart
toend
(inclusive). - For each number in the loop, check if it is an Armstrong number using the
isArmstrongNumber
function. If true, append it to the slice of Armstrong numbers. - Return the slice of Armstrong numbers.
- In the main function, call the
findArmstrongNumbers
function with sample values and print the results.
Go Program
package main
import (
"fmt"
"math"
)
func isArmstrongNumber(num int) bool {
originalNum := num
var sum int
numDigits := int(math.Log10(float64(num))) + 1
for num != 0 {
digit := num % 10
sum += int(math.Pow(float64(digit), float64(numDigits)))
num /= 10
}
return sum == originalNum
}
func findArmstrongNumbers(start, end int) []int {
var armstrongNumbers []int
for i := start; i <= end; i++ {
if isArmstrongNumber(i) {
armstrongNumbers = append(armstrongNumbers, i)
}
}
return armstrongNumbers
}
func main() {
// Define the interval
start, end := 100, 9999
// Find all Armstrong numbers in the interval
armstrongNumbers := findArmstrongNumbers(start, end)
fmt.Printf("Armstrong numbers between %d and %d are: %v\n", start, end, armstrongNumbers)
}
Output
Armstrong numbers between 100 and 9999 are: [153 370 371 407 1634 8208 9474]