自幂数【题解】
作者:互联网
自幂数,也称Armstrong数,是指一个 n 位数,它的每个位上的数字的n 次幂之和等于它本身。
要求程序输入一个正整数m(m≤1000000),按照指定格式输出m以内所有的自幂数。
#include<stdio.h>
typedef long long ll;
ll qpower(ll a, ll b) {
ll ans = 1ll;
while(b) {
if(b & 1) {
ans *= a;
}
b >>= 1;
a *= a;
}
return ans;
}
int check(ll num, ll wei) {
ll t = 1;
ll ans = 0;
ll tmp = num;
while(num) {
ans += qpower((num % 10), wei);
num /= 10;
t++;
if(ans > tmp) {
return 0;
}
}
if(ans == tmp) {
return 1;
}
return 0;
}
int main () {
ll num;
printf("Please input a positive number:");
scanf("%lld", &num);
ll i = 0;
ll wei = 1;
ll cem = 10;
ll tmp = 1;
ll isok = 0;
printf("The Armstrong number within %lld are:", num);
for(i = 0; i < num; ++i) {
if(i != 0 && i % cem == 0) {
if(!isok) {
printf("\nn=%lld:No number!", wei);
}
isok = 0;
wei++;
cem *= 10;
tmp = 1;
}
if(check(i, wei)) {
if(tmp) {
printf("\nn=%lld:", wei);
tmp = 0;
isok = 1;
}
printf("%lld ", i);
}
}
if(!isok) {
printf("\nn=%lld:No number!", wei);
}
printf("\n");
return 0;
}
标签:tmp,题解,ll,printf,num,ans,wei,自幂 来源: https://blog.csdn.net/qq_43591782/article/details/121698621