今天在QQ群里看到一道题目
给出四个整数变量,0 <= a, b, c, d, <= 3000,找出所有满足a^3 + b^3 = c^3 +d^3的数,要求计算次数最少,四重循环不要
一看非常简单的题目,但是后面那几个字汗颜。。。。不要4个for →_→ 好吧。。考虑算法解决
首先我考虑 到的是 因式分解。。这里不写了。。。后来 用forforforfor 写一个例子 ( 1 12 9 10)发现。。。恩 不靠谱,,于是 继续想(→_→此段 凑字数)
然后根据题目 分析,a^3+b^3==c^3+d^3 那么 如果我把 a^3 记录下来 ,是不是 就不用循环了。。。。
如果 考虑 a^3== x的话,那么 x1+x2=x3+x4 ,如果我把 x1+x2 记录 到数组中 那么 对这个数组 排序,判断 和相同的 数,不就是 解决 这题目了。。。那 1 12 9 10 作为例子。
1^3+12^3=1729 记录 1729、1、12 ,9^3+10^3=1729 记录 1729、9、10 因为 Sum 相同,所以输出 这记录的a,b ,c,,d 解决问题。。。(→_→ 我的语言 表达 太弱)
我这里用了 自己写的 一个类存放 数据 →_→ X 代表第一个数 Y 代表第二个数 Sum 代表 3次幂和
上代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 int n = 3000; 6 List<XYAndSum> list = new List<XYAndSum>(); 7 for (int i = 1; i < n; i++) 8 { 9 for (int j = i; j < n; j++) 10 { 11 list.Add(new XYAndSum(i, j)); 12 } 13 } 14 15 ////针对 Sum 排序 16 #region 针对 Sum 排序 17 list.Sort(new Comparison<XYAndSum>( 18 (x, y) => 19 { 20 if (x.Sum == y.Sum) 21 { 22 return 0; 23 } 24 else if (x.Sum > y.Sum) 25 { 26 return 1; 27 } 28 else 29 { 30 return -1; 31 } 32 } 33 )); 34 #endregion 35 36 var count = list.Count; 37 //寻找 Sum相同值 38 #region 寻找 Sum相同值 39 40 var begin = 0; 41 var end = 1; 42 while (end<count) 43 { 44 if (list[begin].Sum==list[end].Sum) 45 { 46 end++; 47 while (list[begin].Sum==list[end].Sum) 48 { 49 end++; 50 } 51 //Console.WriteLine("{0},{1}", begin, end-1); 52 PrintReslut(begin, end - 1, list); 53 begin = end; 54 end++; 55 } 56 else 57 { 58 begin++; 59 end++; 60 } 61 62 63 } 64 #endregion 65 } 66 67 public static void PrintReslut(int begin,int end,List<XYAndSum> list) 68 { 69 for (int i = begin; i <= end; i++) 70 { 71 for (int j = i+1; j <= end; j++) 72 { 73 Console.WriteLine("a : {0} b : {1} c : {2} d : {3}",list[i].X,list[i].Y,list[j].X,list[j].Y); 74 } 75 } 76 77 } 78 79 } 80 81 82 /// <summary> 83 /// 存放的 数据结构 84 /// </summary> 85 class XYAndSum 86 { 87 public int X { get; set; } 88 89 public int Y { get; set; } 90 91 public int Sum { get; set; } 92 93 public XYAndSum(int x,int y) 94 { 95 X = x; 96 Y = y; 97 Sum = GetReslut(x) + GetReslut(y); 98 } 99 100 private int GetReslut(int x) 101 { 102 return x * x * x; 103 } 104 }