求出0~999999之间的所有“水仙花数”并输出。
“水仙花数”是指一个三位数,其各位数字的立方和确好等于该数本身,
如:153=1 ^ 3+5 ^ 3+3 ^ 3 ? ,则153是一个“水仙花数”。
C语言程序:
int main() { int i = 0; for (i = 0; i < 1000000; i++) { int count = 1; int tmp = i;//11 int sum = 0; //计算几位数 while (tmp / 10)//10 11 { count++;//2 tmp /= 10;//1 } //计算每位数的次方和 tmp = i;//10 while (tmp) { sum +=pow(tmp % 10, count);//pow(a,b)函数计算a的b次方的值,头文件 math.h tmp = tmp / 10; } //比较 if (i == sum) printf("%d ", i); } system("pause"); return 0; }
Java程序:
public class Text { public static void main(String[] args) { int i = 0; for (i = 0; i <= 999; i++) { int temp = i; //double sum = 0; //判断位数:10~99 只判断一次10 三位数只判断一次100 //10%10==0;100%10==0,但中间会有20%10==0所以就有 //20/10=2(20>>1),30/10=3;10/10=1(10>>1),100/10=10(100>>1) //所以 就要加一个条件使20,30...不能进循环,让10和100要进循环 int count = 1; //存储一个数的位数 //int j = 0; //while (((temp % 10) == 0) && ((temp / 10) == (Math.pow(10,j)))) { while (temp / 10 != 0){ count++; temp /= 10; // j++; } // System.out.println(count); //求余进行判断 // int a = i % 10; // int b = (i / 10) % 10; // int c = (i / 100); // if (i == Math.pow(a,count) + Math.pow(b, count) + Math.pow(c, count)) { // System.out.print(i + " "); // } } } }
来源:51CTO
作者:
链接:https://blog.csdn.net/weixin_45479045/article/details/100859451