有道難題第二題演算法

來源:互聯網
上載者:User

 

第二道演算法題(500分)

題目要求:雙倍超立方數是指一個正整數可以正好被拆分為兩種不同的a^3+b^3的方式,其中a,b均為整數且0<a<=b。對於任何一個指定的 int n, 返回所有的小於等於n的雙倍超立方數的個數。

 

Code
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Collections;
 6 
 7 namespace ConsoleApplication1
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             int n = int.Parse(Console.ReadLine());
14 
15             System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
16             watch.Start();
17             List<int> baseNums = new List<int>();
18             Dictionary<int, int> Results = new Dictionary<int, int>();
19             int ResultCount = 0;
20 
21             for (int a = 1; a * a * a < n; a++)
22             {
23                 baseNums.Add(a * a * a);
24             }
25             for (int a = 0; a < baseNums.Count; a++)
26             {
27                 for (int b = a; b < baseNums.Count; b++)
28                 {
29                     int _temp = baseNums[a] + baseNums[b];
30                     if (_temp < n + 1)
31                     {
32                         if (Results.ContainsKey(_temp))
33                         {
34                             Results[_temp] += 1;
35                         }
36                         else
37                         {
38                             Results.Add(_temp, 1);
39                         }
40                     }
41                 }
42             }
43 
44             foreach (var item in Results)
45             {
46                 if (item.Value == 2)
47                 {
48                     ResultCount += 1;
49                 }
50             }
51 
52             watch.Stop();
53             Console.WriteLine("we found {0} results in {1} milliseconds", ResultCount, watch.ElapsedMilliseconds);
54         }
55     }
56 }
57 

這一題大概是這麼算的吧。。有更好的演算法嗎?還望指教

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.