Problem16

30分プログラム、その282。Problem16 via Project EulerGaucheで。

215 = 32768 であり、これの各数字の合計は 3 + 2 + 7 + 6 + 8 = 26 となる。
同様にして、21000 の各数字の合計を求めよ。

特に問題なく解けた。ポイントを述べるならば、数字を桁ごとに分解するのにunfoldを用いたことと、unfoldに渡す関数にcutを使って短かく書いたあたり。unfoldを思いついた人は、foldを思いついた人と同じぐらい天才だと思う。cut/cuteを思いついた人も相当センスがいい。

使い方

$ time gosh 282-problem16.scm 1000
1366
gosh 282-problem16.scm 1000  0.05s user 0.02s system 49% cpu 0.156 total

ソースコード

#! /opt/local/bin/gosh
;; -*- mode:scheme; coding:utf-8 -*-
;;
;; problem16.scm -
;;
;; Copyright(C) 2008 by mzp
;; Author: MIZUNO Hiroki / mzpppp at gmail dot com
;; http://howdyworld.org
;;
;; Timestamp: 2008/04/07 22:46:44
;;
;; This program is free software; you can redistribute it and/or
;; modify it under MIT Lincence.
;;
(use srfi-1)

(define (solve n)
  (apply + (unfold
	    (cut eq? <> 0)
	    (cut modulo <> 10)
	    (cut quotient <> 10)
	    (expt 2 n))))

(define (main argv)
  (print (solve (string->number (cadr argv)))))