Problem 26
- 投稿者 : rei
Original
A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given:
1/2 = 0.5
1/3 = 0.(3)
1/4 = 0.25
1/5 = 0.2
1/6 = 0.1(6)
1/7 = 0.(142857)
1/8 = 0.125
1/9 = 0.(1)
1/10 = 0.1
Where 0.1(6) means 0.166666…, and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle.Find the value of d 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.
和訳
単位分数とは分子が1の分数である。分母が2から10の単位分数を10進数で表記すると次のようになる。
1/2 = 0.5
1/3 = 0.(3)
1/4 = 0.25
1/5 = 0.2
1/6 = 0.1(6)
1/7 = 0.(142857)
1/8 = 0.125
1/9 = 0.(1)
1/10 = 0.1
0.1(6)は 0.166666… という数字であり、1桁の循環節を持つ。1/7 の循環節は6桁ある。d < 1000 なる 1/d の中で循環節が最も長くなるような 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 40 41 42 43 44 45 46 47 48 | using System; using System.Linq; namespace ProjectEuler { class Problem26 : Problem{ public Problem26() { int answer = 0, length = 0; for (int i = 1; i < 1000; i++) { int rep = CountRepeat(i); if (rep > length) { length = rep; answer = i; } } Console.WriteLine("> " + answer); } public int CountRepeat(int n) { int x = 10, length = 0; string repeat = ""; for (;x != 0;) { while (x < n) x *= 10; repeat += (x / n); if (IsRepeat(repeat, out length)) { break; } x = x % n; } return length; } public bool IsRepeat(string s, out int length) { string rev = new string(s.ToCharArray().Reverse().ToArray()), sub, nextsub; length = 0; for (int i = 5; i<s.Length/2;i++ ) { sub = rev.Substring(0, i + 1); nextsub = rev.Substring(i + 1, sub.Length); if (sub == nextsub) { length = sub.Length; return true; } } return false; } } } |
スマートな解き方が分からなかったので、かなり強引にやってます。
誰か解法を教えてください。


コメントはまだありません。