这题太不科学了……可能是因为我对c了解还不够……
用了记忆化搜索……先是递归(图样图森破)
显然是栈不够深,随后转为普通while flow control, 这个明明是正确的解法啊……结果经常在mingw下停止工作,目测也是越界什么错误的……
ide有时候会很有用的~可惜我目前还算是不想用,在linux下编程是有时会方便……
但我今天本来没想编程的……
(以上废话)
之前不是显示不出大数据咩~
于是我就输出答案,看看规律~想想数学的方法……结果一头雾水
然后就因为上课忙,一直放着没动……
然后我就去看了jason(不知道是谁……)的blog
这不科学……代码为什么这么乱……
重上……
import time
start = time.time()
def collatz(n, count=1):
while n > 1:
count += 1
if n % 2 == 0:
n = n/2
else:
n = 3*n + 1
return count
max = [0,0]
for i in range(1000000):
c = collatz(i)
if c > max[0]:
max[0] = c
max[1] = i
elapsed = (time.time() - start)
print "found %s at length %s in %s seconds" % (max[1],max[0],elapsed)
这是最基本的方法了~
然后下面他用了一种奇怪的方法, 上code
import time
start = time.time()
limit = 1000000
collatz_length = [0] * limit
collatz_length[1] = 1
max_length = [1,1]
for i in range(1,1000000):
n,s = i,0
TO_ADD = [] # collatz_length not yet known
while n > limit - 1 or collatz_length[n] < 1: #用来保护数组,同时做预处理
TO_ADD.append(n)
if n % 2 == 0: n = n/2
else: n = 3*n + 1
s += 1
# collatz_length now known from previous calculations
p = collatz_length[n]
for j in range(s):
m = TO_ADD[j] #步骤中的每一个出现的数据,都进行记忆化
if m < limit:
new_length = collatz_length[n] + s - j
collatz_length[m] = new_length
if new_length > max_length[1]: max_length = [i,new_length]
elapsed = (time.time() - start)
print "found %s at length %s in %s seconds" % (max_length[0],max_length[1],elapsed)
直接用list记录过程,把原先深度优先搜索,优化了一下,嗯……这才是合理的记忆化。用for语句模拟了深搜return时的
f[n] = find_len(n);
return(f[n]);
然后呢……我就懒得写……朴素方法在跑~
等我快写完这篇文章的时候……依旧没有跑出来……所以说不科学……
算了,不让他跑了~上一个之前写的图样图森破的记忆化深搜。
额……找不到了……emacs的undo
c-u 100 c-x u
经常会退的不是太多……就是太少……不退了~
#include <stdio.h>
#include <stdlib.h>
int f[20000000];
int
find_len(m)
{
int times = 0;
int n = m;
while (n>1)
{
if (f[n] != 0)
{
times += f[n];
return times;
}
if (n % 2 == 0)
n = n / 2;
else n= n * 3 + 1;
times++;
}
f[m] = times;
return(times);
}
int
main()
{
int max = 1, x = 0;
int now = 0, i;
for (i=0;i<1000000;i++)
f[i] = 0;
f[1] = 1;
for (i=1000; i>0;i--)
{
now = find_len(i);
if (max<now)
{
max = now;
x = i;
}
//printf("%d %d\n", i ,now);
}
printf("%d %d\n", x, max);
}
你说我要不要试试用sublime text 2写写代码试试?看似挺好玩的~
总之这题悲剧……不仅空了好久没做……而且还做悲剧了……