立方變自身
觀察下面的現象,某個數字的立方,按位累加仍然等於自身。
1^3 = 1
8^3 = 512 5+1+2=8
17^3 = 4913 4+9+1+3=17
...
請你計算包括1,8,17在內,符合這個性質的正整數一共有多少個?
請填寫該數字,不要填寫任何多余的內容或說明性的文字。
分析:這里使用到了一個while循環,作用是求得該立方數的各個位數之和,這個算法很好用的!!
代碼附上:
import java.util.Scanner; public class test6 { static int count=0; public static void main(String[] args){ for(int i=1;i<100000;i++){ int ii=(int)Math.pow(i, 3); int temp=0; while(ii!=0){ temp+=ii%10; ii=ii/10; } if(temp==i){ count++; System.out.println(i); } } System.out.println("一共有:"+count); } }
執行結果圖如下: