水仙花數既是各位數字立方和等於其本身的三位數,雖然用數學方程可以求解,但過程極其複雜。不如用
c++做一個for循環程序,用枚舉的方法求出所有的水仙花數:
#include<iostream>
using namespace std;
int main(){
for(int fir=1;fir<10;fir++){
for(int sec=0;sec<10;sec++){
for(int thi=0;thi<10;thi++){
if(fir*fir*fir+sec*sec*sec+thi*thi*thi==fir*100+sec*10+thi){
cout<<fir*100+sec*10+thi<<endl;
}
}
}
}
}
using namespace std;
int main(){
for(int fir=1;fir<10;fir++){
for(int sec=0;sec<10;sec++){
for(int thi=0;thi<10;thi++){
if(fir*fir*fir+sec*sec*sec+thi*thi*thi==fir*100+sec*10+thi){
cout<<fir*100+sec*10+thi<<endl;
}
}
}
}
}
相信各位大俠一定有更好的算法,希望能寫下自己的見解!