Introduction
"Armstrong number" is an n-digit number that is equal to the sum of the nth powers of its individual digits.
Example1: 153 - Total Number of digits = 3
13 + 53 +33 = 1+125+27= 153 - Armstrong Number
Example2: 1634 - Total Number of digits = 4
14 + 64 +34 + 44= 1+1296+81+256= 1634 - Armstrong Number
Example3: 123 => 13 + 23 +33 = 1+8+27= 36 - Not Armstrong number
Some of more Armstrong numbers are 153, 370, 371, 407, 1634, 8208, 9474, 54748, 92727, 93084, 548834, 1741725, 4210818, 9800817, 9926315, 24678050, 24678051, 88593477, 146511208, 472335975, 534494836, 912985153, 4679307774.
Now we will write a program to check whether given number is Armstrong number or Not using C# and VB.NET.
C#.NET Program:
namespace DotNetMirror
{
class ArmStrongNumber
{
public static void Main()
{
Console.WriteLine("********** ArmStrong Number Check Example ********");
Console.WriteLine("Enter Number to Want to check");
int numberToCheck = int.Parse(Console.ReadLine());
int lenthOfNumber = numberToCheck.ToString().Length;
double reminder = 0;
double sum = 0;
int tempNo = numberToCheck;
while (tempNo > 0)
{
reminder = tempNo % 10;
sum = sum + Math.Pow(reminder, lenthOfNumber);
tempNo = tempNo / 10;
}
if (sum == numberToCheck)
{
Console.WriteLine("The given Number {0} is a Armstrong Number", numberToCheck);
}
else
{
Console.WriteLine("The given Number {0} is NOT a Armstrong Number", numberToCheck);
}
Console.ReadLine();
}
}
}
VB.NET Version:
Namespace DotNetMirror
Class ArmStrongNumber
Public Shared Sub Main()
Console.WriteLine("********** ArmStrong Number Check Example ********")
Console.WriteLine("Enter Number to Want to check")
Dim numberToCheck As Integer = Integer.Parse(Console.ReadLine())
Dim lenthOfNumber As Integer = numberToCheck.ToString().Length
Dim reminder As Double = 0
Dim sum As Double = 0
Dim tempNo As Integer = numberToCheck
While tempNo > 0
reminder = tempNo Mod 10
sum = sum + Math.Pow(reminder, lenthOfNumber)
tempNo = tempNo \ 10
End While
If sum = numberToCheck Then
Console.WriteLine("The given Number {0} is a Armstrong Number", numberToCheck)
Else
Console.WriteLine("The given Number {0} is NOT a Armstrong Number", numberToCheck)
End If
Console.ReadLine()
End Sub
End Class
End Namespace
Output:
Note: In simpler way people refers Armstrong number as "sum of cubes of individual digits of a number is equal to the number itself". In this case, replace sum = sum + Math.Pow(reminder, lenthOfNumber) with sum = sum + (reminder * reminder * reminder) in the code.