JS 水仙数

水仙花数是指一个 n 位数 ( n≥3 ),它的每个位上的数字的 n 次幂之和等于它本身。(例如:1^3 5^3 3^3 = 153)
  三位的水仙花数共有4个:153,370,371,407
  四位的水仙花数共有3个:1634,8208,9474
  五位的水仙花数共有3个:54748,92727,93084
  六位的水仙花数只有1个:548834
  七位的水仙花数共有4个:1741725,4210818,9800817,9926315
  八位的水仙花数共有3个:24678050,24678051,88593477
  ……

 

 1 //水仙数 by Diva
 2     for (var i = 0; i <= 1000000; i++) {
 3         var str = i.toString();
 4         var sum = 0;
 5         for (var j = 0; j < str.length; j++) {
 6             sum += Math.pow(str.charAt(j), str.length);
 7         }
 8         if (i == sum) {
 9             document.write(i + "<br>");
10         }
11     }

 

 1 //水仙数 by Demon
 2     var narcissus = function (length) {
 3         var maxStr = '9999999999999999',
 4                 minStr = '1000000000000000',
 5                 max = Number(maxStr.slice(0, length)),
 6                 min = Number(minStr.slice(0, length - 1)),
 7                 i, sum, result = [];
 8         while (min < max) {
 9             sum = 0;
10             a = min.toString();
11             for (i = 0; i < length; i += 1) {
12                 sum += Math.pow(a[i], length);
13             }
14             if (sum === min) {
15                 result.push(min);
16             }
17             min += 1;
18         }
19         alert(result);
20     };

 

 

 

 

posted @ 2013-05-13 23:57  migo_  阅读(348)  评论(0编辑  收藏  举报