水仙花数的定义如下(狭义):水仙花数(Narcissistic number)也被称为超完全数字不变数(pluperfect digital invariant, PPDI)、自恋数、自幂数、阿姆斯壮数或阿姆斯特朗数(Armstrong number),水仙花数是指一个 3 位数,它的每个位上的数字的 3次幂之和等于它本身。例如:1^3 + 5^3+ 3^3 = 153。
要求编程求出1000以内的所有水仙花数
样例输入:无
样例输出:
153
370
371
407
C++代码如下
#include<bits/stdc++.h>
using namespace std;
bool ok(int n){
int a=n/100,b=n%100/10,c=n%10;
if(pow(a,3)+pow(b,3)+pow(c,3)==n){
return 1;
}
return 0;
}
main(){
for(int i=100;i<1000;i++){
if(ok(i)==1){
cout<<i<<"\n";
}
}
}
任何位数代码
#include<bits/stdc++.h>
using namespace std;
bool ok(int n){
int w=0,p=n,q=n,s=0;
while(p){
w++;
p/=10;
}
while(q){
s+=pow(q%10,w);
q/=10;
}
if(s==n){
return 1;
}
return 0;
}
main(){
ios::sync_with_stdio(0);
int n;
cin>>n;
for(int i=100;i<=n;i++){
if(ok(i)==1){
cout<<i<<"\n";
}
}
}