📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
1. Introduction
An Armstrong number (of a given number of digits) is an integer such that the sum of its own digits each raised to the power of the number of digits is equal to the number itself. For instance, 153 is an Armstrong number since 1^3 + 5^3 + 3^3 = 153.
In this blog post, we'll dive into the properties of an Armstrong number and present a Go program that checks if a given number is Armstrong or not.
2. Program Overview
Our Go program will:
1. Prompt the user to input a number.
2. Check if the given number is an Armstrong number.
3. Display the result to the user.
3. Code Program
// Declare the package name
package main
// Import necessary packages for input-output and mathematical operations
import (
"fmt"
"math"
)
// Function to check if a number is an Armstrong number
func isArmstrong(num int) bool {
originalNum := num
sum := 0
n := len(fmt.Sprintf("%d", num))
for num != 0 {
digit := num % 10
sum += int(math.Pow(float64(digit), float64(n)))
num /= 10
}
return sum == originalNum
}
// Main function where the program execution starts
func main() {
var num int
fmt.Print("Enter a number: ")
fmt.Scan(&num)
if isArmstrong(num) {
fmt.Printf("%d is an Armstrong number.\n", num)
} else {
fmt.Printf("%d is not an Armstrong number.\n", num)
}
}
Output:
If you input the number 153: Enter a number: 153 153 is an Armstrong number.
4. Step By Step Explanation
1. Setting Up: The program starts by specifying the package and importing necessary libraries.
2. Armstrong Checker Function: isArmstrong function calculates the sum of the digits of the number raised to the power of the total number of digits and checks if this sum is equal to the original number.
3. User Interaction: The main function prompts the user to enter a number, and then it uses the isArmstrong function to check if the entered number is an Armstrong number. It then displays the result.
By understanding this program, you'll be able to appreciate the beauty of numbers and how simple logic can unravel such intriguing mathematical properties.
Comments
Post a Comment
Leave Comment