Go Language - Program to Check Armstrong Number
Hello everyone, today we will create a Go program to check if the given number is an Armstrong number or not.
An Armstrong number is a positive n-digit number that is equal to the sum of the nth powers of their digits.
For example,
- 2 is an Armstrong number.
2 * 1 = 2
- 1634 is an Armstrong number.
1 + 1296 + 81 + 256 = 1643
- 407 is an Armstrong number.
64 +0+ 343 = 407
Some other Armstrong numbers are 1, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 4071634, 8208, 9474, 54748, 92727, 93084, 548834, 1741725, 4210818, 9800817, 9926315, 24678050, 24678051, 88593477, 146511208, 472335975, 534494836.
Example 1: Let’s create a Go program that checks if the given number is an Armstrong number or not.
/* Go program that checks if the given number is an * Armstrong number or not. */package main
import "fmt"
// Main functionfunc main() { IsArmstrong(371) IsArmstrong(431) IsArmstrong(1) IsArmstrong(1634)}
// Function to calculate x raised to the power yfunc Power(x int, y int) int { if y == 0 { return 1 } if y%2 == 0 { return Power(x, y/2) * Power(x, y/2) } return x * Power(x, y/2) * Power(x, y/2)}
//Function to calculate order of the numberfunc Order(x int) int { n := 0 for x != 0 { n++ x = x / 10 } return n}
//Function to check if the number is Armstrong or notfunc IsArmstrong(x int) {
// Calling order function n := Order(x) temp, sum := x, 0 for temp != 0 { r := temp % 10 sum = sum + Power(r, n) temp = temp / 10 }
// If satisfies Armstrong condition if sum == x { fmt.Println(x, "is an Armstrong") } else { fmt.Println(x, "Not an Armstrong") }}
Output:
Example 2: Input number from standard input,
/* Go program that checks if the number from the standard input is an * Armstrong number or not. */package main
import "fmt"
// Main functionfunc main() { var number int fmt.Println("Enter an integer value : ")
_, err := fmt.Scanf("%d", &number)
if err != nil { fmt.Println(err) }
IsArmstrong(number)}
// Function to calculate x raised to the power yfunc Power(x int, y int) int { if y == 0 { return 1 } if y%2 == 0 { return Power(x, y/2) * Power(x, y/2) } return x * Power(x, y/2) * Power(x, y/2)}
//Function to calculate order of the numberfunc Order(x int) int { n := 0 for x != 0 { n++ x = x / 10 } return n}
//Function to check if the number is Armstrong or notfunc IsArmstrong(x int) {
// Calling order function n := Order(x) temp, sum := x, 0 for temp != 0 { r := temp % 10 sum = sum + Power(r, n) temp = temp / 10 }
// If satisfies Armstrong condition if sum == x { fmt.Println(x, "is an Armstrong") } else { fmt.Println(x, "Not an Armstrong") }}