いわゆる卍研究所。
In: Project Euler
9 1月 2010Project EulerをClojureでおさらいシリーズ。
Problem 16
日本語訳:
215 = 32768 の各桁の数字の和は 3 + 2 + 7 + 6 + 8 = 26 である。
21000 の各桁の数字の和を求めよ。
何の問題もない。big-integerバンザイ。
以前Rubyで解いたもの:
#!/usr/bin/env ruby p (2**1000).to_s.split('').inject(0){|s,x| s + x.to_i}
こういうときのRubyの記述力は異常。
今回はClojureで:
(ns euler.p016) (defn pow "Return the N-th power of A." [a n] (apply * (replicate n a))) (defn sum-of-digits "Return the sum of each digits of N." [n] (apply + (map #(Integer. (str %)) (str n)))) (println "Answer : " (sum-of-digits (pow 2 1000)))
Project Euler では各桁を合計する処理がたびたび必要になるので sum-of-digits はライブラリ化したほうがいいのかも。
私 manjilab のポータル的サイトになっております。日々気付いたこと、考えたこと、発表したいものを載せていきます。