This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defun factorial (n) | |
(defun i_factorial (k acc) | |
(if (= 0 k) | |
acc | |
(i_factorial (- k 1) (* k acc)))) | |
(i_factorial n 1)) | |
(defun digits (n) | |
(defun i_digits (k acc) | |
(if (= 0 k) | |
acc | |
(i_digits (truncate k 10) (cons (mod k 10) acc)))) | |
(i_digits n '())) | |
(defun digits_s (n) | |
(mapcar | |
#'(lambda (k) (parse-integer (string k))) | |
(coerce (write-to-string n) 'list))) | |
(format T "~D~%" | |
(time (reduce | |
'+ | |
(mapcar | |
#'(lambda (n) | |
(reduce | |
'+ | |
(digits_s (factorial n)))) | |
'(1 12 123 1234 12345 123456))))) |
Evaluation took: 7.762 seconds of real time 7.565354 seconds of total run time (7.363660 user, 0.201694 system) [ Run times consist of 0.399 seconds GC time, and 7.167 seconds non-GC time. ] 97.46% CPU 17,812,436,719 processor cycles 177 page faults 15,624,347,568 bytes consed 2652733Almost similar results I've got from Go program:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"math/big" | |
"strings" | |
"strconv" | |
"time" | |
) | |
func Factorial(n *big.Int) *big.Int { | |
var unit = big.NewInt(1) | |
var acc *big.Int = big.NewInt(1) | |
var t = n | |
for t.Cmp(unit) == 1 { | |
acc.Mul(acc, t) | |
t.Sub(t, unit) | |
} | |
return acc | |
} | |
func SumDigits(n string) int64 { | |
var r int64 | |
l := strings.Split(n, "") | |
for i := 0; i < len(l); i++ { | |
d, _ := strconv.ParseInt(l[i], 10, 0) | |
r += d | |
} | |
return r | |
} | |
func main() { | |
var s int64 = 0 | |
t1 := time.Now() | |
n := []int64{1, 12, 123, 1234, 12345, 123456} | |
for i := 0; i < len(n); i++ { | |
r := Factorial(big.NewInt(n[i])) | |
s += SumDigits(r.String()) | |
} | |
t2 := time.Now() | |
fmt.Printf("Elapsed time: %v\n", t2.Sub(t1)) | |
fmt.Println(s) | |
} |
Elapsed time: 4.509443s 2652733But strangely Clojure, Haskell and Julia have got some very strange behavior. Till 12345! everything seems to be ok (though for Clojure it takes almost 1.5 sec to calculate while Lisp done it in 0.091 seconds of real time). But when we get 123456! Clojure needs almost 1 minute, Haskell and Julia just plainly refused to calculate. Even in case of Julia it was not so plainly cause it decided to eat almost all memory.