カプレカ数
問題
カプレカ数を計算してみよう。
入力
・3桁の整数値
・整数値以外、負の値の場合は再入力を求める
出力
・カプレカ操作の式
・式がループ状態になれば出力を止める
カプレカ数
・3桁で、同じ数字がない数(322や858、333等はだめ)を選ぶ
例として354の場合。
1) 数字を並び替え、最大値543と、最小値345を得る
2) 大きい数から小さい数を引き、
543-345 = 198
3) 答えの198に 1)と2)の操作を再び加える
891 - 198 = 643
4)以下、この操作を繰り返すと、ある値でループ状態になる
5)このループする値がカプレカ数
例
数値を入力してください(100 - 999) >154 541 - 145 = 396 963 - 369 = 594 954 - 459 = 495
解答例
using System; namespace KaprekarNumber { class Program { static void Main(string[] args) { Kaprekar kap; kap = new Kaprekar(ReadNumber()); while (kap.isLoop == false) { Console.WriteLine(kap.Next()); } } static int ReadNumber() { bool loop = true; int n; do { Console.WriteLine("数値を入力してください(100 - 999)"); loop = !int.TryParse(Console.ReadLine(),out n); if ((n < 100) | (n > 999)) loop = true; } while (loop); return n; } } public class Kaprekar { private int n; public String Formula { get; set; } public bool isLoop { get; set; } public Kaprekar(int n) { this.n = n; this.Formula = string.Empty; this.isLoop = false; } //カプレカ操作 public String Next() { int answer; CNumberSort cns = new CNumberSort(n); int m1 = cns.Max; int m2 = cns.Min; answer = m1 - m2; this.Formula = String.Format("{0} - {1} = {2}", m1, m2, answer); cns.SetValue(answer); if ( cns.Max == m1) this.isLoop = true; n = answer; return this.Formula; } } //数字ソートクラス public class CNumberSort { public int value; public int Max; public int Min; public CNumberSort(int n) { this.value = n; this.Max = 0; this.Min = 0; SetValue(); } public void SetValue(int n) { this.value = n; SetValue(); } private void SetValue() { int[] nums = new int[10]; bool minus = false; String s = string.Empty; String minstr = string.Empty; String maxstr = string.Empty; //数字がマイナスの場合 if (value < 0) { minus = true; s = (-value).ToString(); } else { s = value.ToString(); } //char型配列に変換 char[] carray = s.ToCharArray(); //降順ソート Array.Sort(carray); minstr = new String(carray); //昇順ソート Array.Sort(carray, (x, y) => y - x); maxstr = new String(carray); if (minus == false) { this.Max = int.Parse(maxstr); this.Min = int.Parse(minstr); } else { this.Max = -int.Parse(minstr); this.Min = -int.Parse(maxstr); } } } }