トップ «前の日記(2016-03-23(Wed)) 最新 次の日記(2016-03-25(Fri))» 編集

屑俺日記

僕の備忘録(PC、UN*X、ネットワーク関連が中心)なんです。
自分の書いたところは適当(な時とか)に書き換えますので御了承を。


2016-03-24(Thu) 少し冷えてきた

もう少し階乗を

前に書いたかも、はどうでもいい。
以下、gauche。

(define myfact
  (lambda (n)
    (cond
     ((<= n 1) 1)
     (else
      (* n (myfact (- n 1)))))))
gosh> (myfact 100)
93326215443944152681699238856266700490715968264381\
62146859296389521759999322991560894146397615651828\
62536979208272237582511852109168640000000000000000\
00000000
gosh>

EmacsLispで書いた次のスクリプトでは、あまり 大きな数は扱えないかも。

(defun myfact(n)
  (cond
   ((<= n 1) 1)
   (t
    (* n (myfact (- n 1))))))
(myfact 63)
1585267068834414592
 
(myfact 64)
Lisp nesting exceeds `max-lisp-eval-depth'
 
max-lisp-eval-depth
641
 
(setq max-lisp-eval-depth 1000)
(myfact 64)
0

再帰は無理か?

なんとなくLISPの真似をしてみた。

#!/usr/bin/env python
from sys import argv
num = int(argv[1])
 
def myfact(x):
  if x <= 1:
   return 1
  else:
   return x * myfact(x - 1)
 
print(myfact(num))
$ python myfact.py 6
720
 
$ python myfact.py 999 | wc
      1       1    2566
 
$ python myfact.py 1000
Traceback (most recent call last):
  File "myfact.py", line 11, in 
    print(myfact(num))
  File "myfact.py", line 9, in myfact
    return x * myfact(x - 1)
  File "myfact.py", line 9, in myfact
    return x * myfact(x - 1)
  File "myfact.py", line 9, i
.
.
.
  File "myfact.py", line 9, in myfact
    return x * myfact(x - 1)
RuntimeError: maximum recursion depth exceeded

このスクリプトをpython3にかけると、998が限界だった。
エラーで検索して、とりあえずの対応。

>>> sys.getrecursionlimit()
1000
>>> sys.setrecursionlimit(2000)

リンクはご自由にどうぞ。でもURLや内容が変った場合はあしからず。

index.htmlは ここから。