星期二 十一月 10, 2009 09:33
一道数学题
有这样一道题:将一个数的末位,放到首位,使得结果是原数的2倍,求这个数。如:21,转换后,变成12,12不是21的2倍,不符合条件。寻找符合条件的答案,乍一想,可能最难的地方是不知道他是一个几位数。这道题是我从柳大侠的博客上剽窃来的一道题,当初人家是用心算给出的结果。很出乎我意料的是,他的答案居然貌似是正确,并且答案的字面让我很震撼:是一个18位数。
我很纳闷,并有些痛苦的感叹。但很快的我决定写一个程序来代替我思考这样一道算术游戏。废话不多说,上代码:
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 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 | using System; using System.Collections.Generic; using System.Text; using System.Collections; using System.IO; namespace mathGame { class findTheNumber { static void Main(string[] args) { findTheNumber f = new findTheNumber(); f.showTheAnswer(); } /** *分析: 设目标为一个N位数,前N-1位为X,末位为Y * 则,原数=10x+y;变换后=10^(N-1)*y+x; * (10x+y)*2=10^(N-1)*y+x * 19x=(10^(N-1)-2)*y * 由y为一个一位数,得到10^(N-1)-2为19的倍数,故有: * */ ArrayList getN() { int n = 2; findTheNumber f = new findTheNumber(); BigInteger a = f.mathPower(n-1)-2; ArrayList al = new ArrayList(); do { if (a % 19 == 0) { al.Add(n); } n++; a=f.mathPower(n-1)-2; }while(a.dataLength<100); return al; } BigInteger mathPower(int n) { BigInteger i ; if (n == 0) return 1; else { return 10 * mathPower(n-1); } } /** * 通过getN()获取N值后,可得N=18,x=一个17位数*y; * 满足题目的y值有2-9; * */ void showTheAnswer() { BigInteger x; int count = 0; findTheNumber f = new findTheNumber(); ArrayList nlist = f.getN(); try { FileStream fs = new FileStream("numGame.txt", FileMode.OpenOrCreate); StreamWriter sw = new StreamWriter(fs); foreach (int n in nlist) { for (int y = 2; y <= 9; y++) { x = (f.mathPower(n - 1) - 2) * y / 19; sw.WriteLine("Answer {0}:{1}", ++count, (10 * x + y)); } } sw.Close(); } catch { Console.WriteLine("异常"); Console.ReadLine(); } } } } |
代码中已经包含了我的具体分析,值得指出的是BigInteger这个类需要自己来实现,否则会在答案输出上只能输出9个答案。(因为long的数值限制)另外,这里附带一个参考答案(1000位数以内的所有答案)下载。参考答案 (30)
- Category: code
- (2) Comments
leslie
十一月 15th, 2009 at 10:18 上午
怎么貌似这个问题你很久前和我说过啊。。。反正也是数字 也是别人心算的
邵 明博
十一月 18th, 2009 at 7:54 下午
是。但是,我现在才有时间来思考,来解决啊。人生的悲哀…