checking armstrong number

The following code is a code of checking armstrong number.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include<iostream>
using namespace std;
 
int power(int c, int d);
 
int main()
{
     int num;
     int f,rem,sum=0,temp,a=0;
 
     cout<<"Enter any number :: ";
     cin>>num;
 
     temp=num;
 
     while(temp != 0)
     {
         temp=temp/10;
         a=a+1;
     }
 
     f=num;
 
     while(f!=0)
     {
         rem=f%10;
         sum = sum + power(rem,a);
         f=f/10;
     }
 
     if( sum == num )
     {
         cout<<"\n The Entered Number [ "<<num<<" ] is an Armstrong number.\n";
     }
     else
     {
         cout<<"\n The Entered Number [ "<<num<<" ] is Not an Armstrong number.\n";
     }
 
     return 0;
}
 
 
int power(int c, int d)
{
    int pow=1;
    int i=1;
    while(i<=d)
    {
      pow=pow*c;
      i++;
     }
     return pow;
}

Could someone please explain. What is the purpose of the following portion of the code?
1
2
3
4
5
 while(temp != 0)
     {
         temp=temp/10;
         a=a+1;
     }
when playing with the digits of an integer, you can %10 to get the lowest order digit and /10 to advance.
so 1234
%10 is 4.
/10 is 123
%10 again is 3
/10 again is 12
... etc

adding one to a is counting how many digits the number has, as if the writer did not know about += and did not know about logs. This implies it was written by a student for homework, or someone in a hurry who coded without thinking. Power isnt optimal either, 2 to the 63 power doe like 50 extra multiplies, though for small powers its fine (eg N to the 10 or less).
Last edited on
Topic archived. No new replies allowed.