Problem 44
- 投稿者 : rei
Original
Pentagonal numbers are generated by the formula, Pn=n(3n1)/2. The first ten pentagonal numbers are:
1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference, 70 – 22 = 48, is not pentagonal.
Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference is pentagonal and D = |Pk – Pj| is minimised; what is the value of D?
和訳
五角数は Pn = n(3n-1)/2で生成される. 最初の10項は
1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...である.
P4 + P7 = 22 + 70 = 92 = P8である. しかし差 70 – 22 = 48は五角数ではない.
五角数のペア PjとPkについて, 差と和が五角数になるものを考える. 差を D = |Pk – Pj| と書く. 差 D の最小値を求めよ.
当てにならないソースコード(C#)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | using System; using System.Collections.Generic; namespace ProjectEuler { class Problem44 : Problem{ public Problem44() { SortedList<long, long> pen = new SortedList<long, long>(); pen.Add(1,1); long answer = 0; while (!Pentagonal(pen, ref answer)); Console.WriteLine("> " + answer); } public bool Pentagonal(SortedList<long, long> penta, ref long ans) { int n = penta.Count + 1; long pn = n * (3 * n - 1) / 2, cmp = 1; for (int i = penta.Count - 1; i>=0;i--) { if (penta.Keys[i] < pn / 2) { cmp = penta.Keys[i]; break; } } foreach (var px in penta) { if (px.Key >= cmp) break; if (penta.ContainsKey(cmp + px.Key)) { if (penta.ContainsKey(cmp - px.Key)) { //Console.WriteLine("{0} - {1} = {2}", cmp, px.Key, cmp - px.Key); ans = cmp - px.Key; return true; } } } penta.Add(pn,pn); return false; } } } |
和と差の条件はクリアしているのですが、
差が最少であるかどうかのチェックを行っていないので厳密には誤りです。
一応正解ではありましたが。

rei@sikios.com
コメントはまだありません。