也发一个有道第二题的算法,练练脑子
第二道算法题(500分)
题目要求:双倍超立方数是指一个正整数可以正好被拆分为两种不同的a^3+b^3的方式,其中a,b均为整数且0<a<=b。对于任何一个指定的 int n, 返回所有的小于等于n的双倍超立方数的个数。
下面是我的算法, 思路其实就是 这里的 ab 两个数一定都不比给出的n的立方根的的整数大
using System;
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
{
countMap.Add(nn, 1);
}
}
else
{
break;
}
}
}
watch.Stop();
Console.WriteLine("we found {0} results in {1} milliseconds", ResultCount, watch.ElapsedMilliseconds);
}
}
}
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
{
countMap.Add(nn, 1);
}
}
else
{
break;
}
}
}
watch.Stop();
Console.WriteLine("we found {0} results in {1} milliseconds", ResultCount, watch.ElapsedMilliseconds);
}
}
}
测试结果 如下图: