













第二道算法题(500分)
题目要求:双倍超立方数是指一个正整数可以正好被拆分为两种不同的a^3+b^3的方式,其中a,b均为整数且0<a<=b。对于任何一个指定的 int n, 返回所有的小于等于n的双倍超立方数的个数。
看到坛子里面有人发的帖子 是关于有道第二题的,饶有兴趣,自己也写了一个算法,效率上面应该比引用文章的效率会高点,具体情况请大家测试吧
引用上述网址的的程序代码 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
下面是我的算法, 思路其实就是 这里的 ab 两个数一定都不比给出的n的立方根的的整数大
using System.Collections.Generic;
using System.Text;namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int n = 475574;
int ResultCount = 0;
System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
watch.Start();
Dictionary<int, int> countMap = new Dictionary<int, int>();
int i = (int)Math.Pow(n, 1.0 / 3.0);
for (; i > 0; i--)
{
int k = i * i * i;
int m = n - k;
for (int x = 1; x <= i; x++)
{
if ((x * x * x) <= m)
{
int nn = (i * i * i) + (x * x * x);
if (countMap.ContainsKey(nn))
{
if (countMap[nn] < 2)
{
ResultCount++;
}
}
else
}
}
}
测试结果 如下图:

此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。