Check Armstrong Number in Go



In this tutorial, we will learn how to check if a number is an Armstrong number in Go. We will cover the basic concept of Armstrong numbers and implement a function to perform the check.


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 check if a number is an Armstrong number 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
}


Example 1: Checking if a number is an Armstrong number

We can create a function to check if a given number is an Armstrong number by calculating the sum of its digits each raised to the power of the number of digits.

For example,

  1. Import the fmt and math packages.
  2. Define a function named isArmstrongNumber that takes one parameter num of type int.
  3. Store the original number in a variable originalNum.
  4. Initialize a variable sum to 0 to hold the sum of the digits raised to the power of the number of digits.
  5. Calculate the number of digits in the number using math.Log10 and add 1.
  6. Use a for loop to iterate through the digits of the number.
  7. In each iteration, extract the last digit of the number, raise it to the power of the number of digits, and add it to sum.
  8. Remove the last digit from the number by dividing it by 10.
  9. After the loop, check if sum is equal to originalNum. If true, return true; otherwise, return false.
  10. In the main function, call the isArmstrongNumber function with sample numbers 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 main() {
    // Sample numbers
    numbers := []int{153, 9474, 9475}

    // Check and print if each number is an Armstrong number
    for _, number := range numbers {
        result := isArmstrongNumber(number)
        if result {
            fmt.Printf("%d is an Armstrong number\n", number)
        } else {
            fmt.Printf("%d is not an Armstrong number\n", number)
        }
    }
}

Output

153 is an Armstrong number
9474 is an Armstrong number
9475 is not an Armstrong number