JavaScript的大数阶乘

一道算法题,以前51js上讨论过。思路就是自己实现乘法运算,如果用递归,如果求1000的阶乘就要出现脚本失控了

 

51JS上最为经典的方法:

   1: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   2: <html xmlns="http://www.w3.org/1999/xhtml">
   3:  <head>
   4:   <title> new document </title>
   5:   <meta name="generator" content="editplus" />
   6:   <meta name="author" content="" />
   7:   <meta name="keywords" content="" />
   8:   <meta name="description" content="" />
   9:  </head>
  10:  
  11:  <body>
  12: <script type='text/javascript'>
  13: function factorial(n) {
  14:     var a = [1];
  15:     for (var i = 1;i<=n ;i++) {
  16:         for (var j = 0, c = 0;j<a.length || c != 0;j++ ) {
  17:             var m = (j < a.length) ? (i*a[j] + c) : c;
  18:             a[j] = m % 10;
  19:             c = (m - a[j]) / 10;
  20:         }
  21:     }
  22:     
  23:     return a.reverse().join("");
  24: }
  25:  
  26: var num = 1000;
  27:  
  28: alert(factorial(num));
  29: </script>
  30:  </body>
  31: </html>
posted @ 2011-03-10 00:37  meteoric_cry  阅读(1416)  评论(0编辑  收藏  举报