I want to find out the first n satisfying
. This is simple and easy material if I use another language, for example, c / C ++, but I do not know how to implement it in 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;
}
I used dropWhile with an ordered list and took 1 to select the first.
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
I know this is terrible. What is the best and most intuitive way to write this?
Re: Thanks for the great answers! The one that uses the fix function seems to be the fastest on my machine (Redhat 6.4 64 bit / 80 GB of memory)
method # 0 accept 1 and dropWhile (my initial implementation)
threshold=0.74999 n=99999 time=52.167 sec
method # 1 using the fix function
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
method # 2 works back
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
method # 3 the imperative way
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, , 150 000 000, ! [f (n) =\frac_ {3n ^ 2 + 5n} ^ {4n ^ 2 + 12n + 8}]. Integer Int, . , , 0.7499999936264...?