I wrote this program in C# to generate Armstrong numbers.I know the addition of extra method is unnecessary but it's something I've just learnt and have been practicing . So the generator only shows number till 9 no matter how large of a limit I give.
using System;
namespace ArmstrongNumberGenerator
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the maximum limit for searching");
int max = Convert.ToInt32(Console.ReadLine());
for (int i = 1; i <= max; i++)
{
if (isArmstrong(i))
Console.WriteLine(i);
}
Console.ReadLine();
}
static bool isArmstrong(int x)
{
int temp = x;
int sum = 0;
while (x!=0)
{ sum = sum + x % 10;
x = x / 10;
}
if (sum == temp)
return true;
else
return false;
}
}
}
I can't see what I am doing wrong.
Explanation for Armstrong-Number:
Sum of the cubes of its digits must equal to the number itself.
For example, 407
is given as input.
4 * 4 * 4 + 0 * 0 * 0 + 7 * 7 * 7 = 407
is an armstrong number.
You need to calculate the sum right:
static bool isArmstrong(int x)
{
int sum = 0;
for (int i = x; i > 0; i = i / 10)
{
sum = sum + (int)Math.Pow(i % 10, 3.0);
}
if (x == sum)
return true;
else
return false;
}
This has following output with your code (except that i incluced 0
which is also an armstrong number):
Enter the maximum limit for searching
9999
0
1
2
3
4
5
6
7
8
9
153
370
371
407
1634
8208
9474