Skip to content

Instantly share code, notes, and snippets.

@thinkphp
Created January 10, 2020 19:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thinkphp/b71cef860eee3db60a5f87c67c3a8544 to your computer and use it in GitHub Desktop.
Save thinkphp/b71cef860eee3db60a5f87c67c3a8544 to your computer and use it in GitHub Desktop.
/*
An Armstrong number is a number that is equal to the sum of digits raise to the power total number of digits in the number.
Some Armstrong numbers: 153, 370, 1634
*/
#include <stdio.h>
#define LL long long
int countDigits(int n) {
int count = 0;
while(n) {
count++;
n/= 10;
}
return count;
};
LL pow2(int a, int b) {
int i, p = 1;
for(i = 1; i <= b; ++i) {
p = p * a;
}
return p;
};
int isArmstrong(int n) {
int sum = 0,
count = countDigits(n), n2 = n;
while(n) {
sum += pow2(n%10, count);
n/=10;
}
if(sum == n2) {
while(n2) {
printf("%d ^ %d + ", n2 % 10, count);
n2 /= 10;
}
return 1;
}
else
return 0;
};
int main() {
int n;
printf("%s", "N=");
scanf("%d", &n);
if(isArmstrong(n)) {
printf("\nThe number is Armstrong.\n");
} else {
printf("\nThe number is not Armstrong.\n");
}
return(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment