A positive integer number N is called as Armstrong if the sum of the cubes of its own digits is equal to the number itself. For example: the number 153 is Armstrong since 13 + 53 + 33 is equal to 1+ 125 + 27 which is equal to 153.
Write a C++ program that reads any positive integer and checks whether this number is Armstrong or not
1
Expert's answer
2014-03-24T11:13:27-0400
#include <iostream> // cout, cin #include <cstdlib> // system #include <cmath> // pow using namespace std;
int arm(int val){ int cval=val; int t=val; int n=0; // n- digit number while(t){t/=10;++n;} int res=0; do{ t=val;//take low order digit res+=(int)pow(double(t),n); val/=10;//shifts by one bit to the right if(res>cval ) return -1; // accelerates by about 30% if the N = 9, it is more likely. }while(val); // check the counting return res; } int main () { int val; cout<<"Enter the number"<<endl; cin>>val; if(arm(val) ==val) cout<<"this number is Armstrong"<<endl; else cout<<"this number is not Armstrong"<<endl; system("pause"); return 0;
Comments
Leave a comment