更新:C ++程序(如下所示)的编译没有附加标志,即g++ program.cpp 。 但是,提高优化级别不会改变以下事实:蛮力运行的速度快于记忆技术(我的计算机上为0.1秒VS 1秒)。
上下文
我尝试计算最长Collatz序列的数量(<100万)。 我写了一个蛮力算法,并将其与建议的优化程序(基本上使用记忆)进行了比较。
我的问题是:蛮力执行比C ++中所谓的优化(记忆化)版本执行得更快的原因可能是什么?
下面是我在机器(Macbook Air)上进行的比较; 时间在注释中的程序代码开头。
C ++(强力)
/**
* runs in 1 second
*/
#include
#include
unsigned long long nextSequence(unsigned long long n)
{
if (n % 2 == 0)
return n / 2;
else
{
return 3 * n + 1;
}
}
int main()
{
int max_counter = 0;
unsigned long long result;
for (size_t i = 1; i < 1000000; i++)
{
int counter = 1;
unsigned long long n = i;
while (n != 1)
{
n = nextSequence(n);
counter++;
}
if (counter > max_counter)
{
max_counter = counter;
result = i;
}
}
std::cout << result << " has " << max_counter << " sequences." << std::endl;
return 0;
}
C ++(记忆)
/**
* runs in 2-3 seconds
*/
#include
#include
int countSequence(uint64_t n, std::unordered_map &cache)
{
if (cache.count(n) == 1)
return cache[n];
if (n % 2 == 0)
cache[n] = 1 + countSequence(n / 2, cache);
else
cache[n] = 2 + countSequence((3 * n + 1) / 2, cache);
return cache[n];
}
int main()
{
uint64_t max_counter = 0;
uint64_t result;
std::unordered_map cache;
cache[1] = 1;
for (uint64_t i = 500000; i < 1000000; i++)
{
if (countSequence(i, cache) > max_counter)
{
max_counter = countSequence(i, cache);
result = i;
}
}
std::cout << result << std::endl;
return 0;
}
在Python中,记忆技术实际上运行得更快。
Python(记忆)
# runs in 1.5 seconds
def countChain(n):
if n in values:
return values[n]
if n % 2 == 0:
values[n] = 1 + countChain(n / 2)
else:
values[n] = 2 + countChain((3 * n + 1) / 2)
return values[n]
values = {1: 1}
longest_chain = 0
answer = -1
for number in range(500000, 1000000):
if countChain(number) > longest_chain:
longest_chain = countChain(number)
answer = number
print(answer)
Python(强力)
# runs in 30 seconds
def countChain(n):
if n == 1:
return 1
if n % 2 == 0:
return 1 + countChain(n / 2)
return 2 + countChain((3 * n + 1) / 2)
longest_chain = 0
answer = -1
for number in range(1, 1000000):
temp = countChain(number)
if temp > longest_chain:
longest_chain = temp
answer = number
print(answer)