我想找出满足的第一个n。如果我使用另一种语言(如c/C++),这是一件简单而容易的事情,但我不知道如何在Haskell中实现它。如何在Haskell中实现带条件休息的循环
#include <iostream>
long double term(int k) { return 1.0/(k*k+2.0*k); }
int main() {
long double total = 0.0;
for (int k=1;;k++) {
total += term(k);
if (total>=2.99/4.0) {
std::cout << k << std::endl;
break;
}
}
return 0;
}
我用dropWhile和一个有序列表,并拿1拿起第一个。
term k = 1.0/(k*k+2.0*k)
termSum n = sum $ take n $ map term [1..]
main = do
let [(n,val)] = take 1 $ dropWhile (\(a,b)->b <= 2.99/4.0) $ map (\n->(n,termSum n)) [1..]
print n
我知道这太可怕了。什么是最好的和直观的方式来写这个?
回复: 谢谢你的好评!使用修复功能的一个似乎是在我的机器最快(红帽6.4 64/80GB存储器)
方法#0取1和dropWhile(我的最初的实施),使用修复功能
threshold=0.74999 n=99999 time=52.167 sec
方法#1
threshold=0.74999 n=99999 time=0.005 sec
threshold=0.74999999 n=101554197 time=1.077 sec
threshold=0.7499999936263 n=134217004 time=1.407 sec
方法#2向后工作
threshold=0.74999 n=99999 time=0.026 sec
threshold=0.74999999 n=101554197 time=21.523 sec
threshold=0.7499999936263 n=134217004 time=25.247 sec
方法#3势在必行方式
threshold=0.74999 n=99999 time=0.008 sec
threshold=0.74999999 n=101554197 time=2.460 sec
threshold=0.7499999936263 n=134217004 time=3.254 sec
RERE: 我注意到,无论执行我使用(修复,势在必行的方式,或递归的方式),如果阈值比0.7499999936264大......它永远不会结束..为了让F(N)大于0.7499999936264,我认为自从![f(n)= \ frac_ {3n^2 + 5n}^{4n^2 + 12n + 8}]之后,我们只需计算高达150,000,000的项。我用Integer代替Int,但它也没有帮助。如果我将阈值设置为大于0.7499999936264 ...,是否有任何原因尚未完成?
我可能用明确的递归来写它。我认为在这里看起来很干净。 –