Identifying Armstrong Numbers in C#: An Efficient Algorithm
Learn how to determine if a number is an Armstrong number (narcissistic number) in C#. This tutorial provides a clear and concise algorithm, demonstrating how to extract digits, perform calculations, and efficiently check if a number meets the Armstrong number criteria.
Checking for Armstrong Numbers in C#
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, 371 is an Armstrong number because 3³ + 7³ + 1³ = 371 (3*3*3 + 7*7*7 + 1*1*1 = 27 + 343 + 1 = 371).
C# Program to Check for Armstrong Numbers
This C# program checks if a given number is an Armstrong number. It does this by extracting each digit, raising it to the power of the number of digits, and summing the results. If the sum equals the original number, the number is an Armstrong number.
C# Code
using System;
public class ArmstrongNumberChecker {
public static void Main(string[] args) {
Console.Write("Enter a number: ");
int number = int.Parse(Console.ReadLine());
if (IsArmstrong(number)) {
Console.WriteLine($"{number} is an Armstrong number.");
} else {
Console.WriteLine($"{number} is not an Armstrong number.");
}
}
public static bool IsArmstrong(int number) {
int originalNumber = number;
int numDigits = number.ToString().Length;
int sum = 0;
while (number > 0) {
int digit = number % 10;
sum += (int)Math.Pow(digit, numDigits);
number /= 10;
}
return originalNumber == sum;
}
}
Conclusion
This program demonstrates a clear and concise approach to identifying Armstrong numbers in C#. The `IsArmstrong()` function efficiently calculates whether a number meets the criteria. The `Main()` function handles user input and displays the results.