「プロジェクトオイラー問17」の編集履歴(バックアップ)一覧に戻る

プロジェクトオイラー問17 - (2014/02/13 (木) 15:40:22) のソース

http://odz.sakura.ne.jp/projecteuler/index.php?cmd=read&page=Problem%2017



Problem 17 「数字の文字数」 †
1 から 5 までの数字を英単語で書けば one, two, three, four, five であり, 全部で 3 + 3 + 5 + 4 + 4 = 19 の文字が使われている.

では 1 から 1000 (one thousand) までの数字をすべて英単語で書けば, 全部で何文字になるか.

注: 空白文字やハイフンを数えないこと. 例えば, 342 (three hundred and forty-two) は 23 文字, 115 (one hundred and fifteen) は20文字と数える. なお, "and" を使用するのは英国の慣習.





解法
100以上ならその文字数を数え、100以上と100以下がともに0でないならandの3を足す。
100以下が19以下ならその場合を足し。
20以上なら2桁+一桁を足す。
とすればまあ普通に解けます。


 toLen10(N,Result):-
 	P1 is N mod 100,
 	P1<20,
 	!,
 	nth0(P1,[0,3,3,5,4,4,3,5,5,4,3,6,6,8,8,7,7,9,8,8],Result).
 toLen10(N,Result):-
  	P10 is (N mod 100)//10,
 	P1  is N mod 10,
 	nth0(P10,[0,0,6,6,5,5,5,7,6,6],Len10),
 	nth0(P1, [0,3,3,5,4,4,3,5,5,4],Len1),
 	Result is Len10+Len1.
 
 toLen100(N,Result):-
  	P is N//100,
 	P2 is N mod 100,
 	nth0(P,[0,10,10,12,11,11,10,12,12,11,11],Len100),
 	((P>0,P2>0) -> Result is Len100+3;Result is Len100).
 
 
 toLen(N,Result):-
 	toLen100(N,Len100),
  	toLen10(N,Len10),
 	Result is Len100+Len10.
 
 saiki(1001,Ans,Ans):-!.
 saiki(N,Sum,Result):-
 	toLen(N,Len),
 	write([N,Sum]),nl,
  	Sum1 is Sum+Len,
 	N1 is N+1,
 	saiki(N1,Sum1,Result).
 
 main17:-saiki(1,0,Ans),write(Ans).