Monday, July 27, 2009

Send Algorithm on Amstrong number and program in C language?

Algorithm on Amstrong number and program in C language

Send Algorithm on Amstrong number and program in C language?
Some references define Armstrong numbers to


have an arbitrary "base" and "power", but to


keep things simple, I'll assume the simpler


definition which uses base 10 numbers with


the "power" being 3. In other words, an


armstrong number is one where the sum of the


cubed digits is equal to the number itself.





For example:





1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153








The simplest "algorithm" is simply to use "brute force".





It would be quite plausible to run a counter from 1 to


N, and for each value extract the digits by successively


dividing by 10.





I think it is easier, however, to run nested loops over


the possible digit values and synthesize the value by


multiplying and adding the digits together.





The accompanying code runs through all of the numbers


up through 4 digits, but a mechanical translation


could add more digits (up to the precision of the


underlying data type). Type "long" will provide


up through 9 digits, though the computation will


take a bit longer.





Note that because of the restrictions of


the yahoo answers page, the following code


is not indented in the normal fashion.





#include %26lt;stdio.h%26gt;





int


main(int argc, char* argv[])


{


 int i0, i1, i2, i3, i4;





 for (i0=0; i0%26lt;10; i0++) {


 long i0c = i0*i0*i0;





 for (i1=0; i1%26lt;10; i1++) {


 long i1c = i1*i1*i1;





 for (i2=0; i2%26lt;10; i2++) {


 long i2c = i2*i2*i2;





 for (i3=0; i3%26lt;10; i3++) {


 long i3c = i3*i3*i3;





 for (i4=0; i4%26lt;10; i4++) {


 long i4c = i4*i4*i4;


 long value = (((i0*10+i1)*10+i2)*10+i3)*10+i4;


 long armstrong = i0c + i1c + i2c + i3c + i4c;


 if (armstrong == value)


  printf("%ld\n", value);


 }


 }


 }


 }


 }


}








$ cc -xO4 arm.c


$ a.out


0


1


153


370


371


407


No comments:

Post a Comment