Article:
Luyện neuron với projecteuler.net
853
tnd.myopenid.com 17Updated over 3 years ago |
http://projecteuler.net tập hợp một số vấn đề có thể dùng để luyện trí não.
Vì đang học Erlang nên thanh thủ thử ứng dụng vào giải quyết các vấn đề trong website trên.
Vấn đề 1: Add all the natural numbers below one thousand that are multiples of 3 or 5.
Cái này có vẻ dễ nhai:
lists:sum([E || E <-lists:seq(1,999), (E rem 3) =:= 0 orelse ( E rem 5) =:= 0 ]).
Giải pháp là dùng list comprehension với lại filter xem số đó có chia hết cho 3 hoặc 5.
Vấn đề 2: Each new term in the Fibonacci sequence is generated by adding the
previous two terms. By starting with 1 and 2, the first 10 terms will
be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
Find the sum of all the even-valued terms in the sequence which do not exceed four million.
Cái này không dễ nhai như cái trên nhưng sau một thời gian vật vã cũng đã ra giải pháp, lý do là vẫn suy nghĩ theo kiểu lập trình imperative và cái virus functionnal nó chưa lây nhiễm vào dây neuron.
next_fibs([E1, E2 | _] = L) ->
[E1 + E2|L].
lt_four_million_fibs([E1 | _] = L) when E1 =< 4000000 ->
lt_four_million_fibs(next_fibs(L));
lt_four_million_fibs([_|L]) ->
L.
even_lt_four_million_fibs() ->
[X || X <- lt_four_million_fibs([2,1]), X rem 2 =:= 0].
problem2() ->
lists:sum(even_lt_four_million_fibs()).
Vấn đề 3: The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
Vấn đề 9: A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
Cách đơn giản nghĩ ra ngay là kiểm tra tất cả các triplet A,B,C thỏa mãn điều kiện trên
pythag(N) ->
[ {A,B,C} ||
A <- lists:seq(1,N-1),
B <- lists:seq(1,N-1),
C <- lists:seq(1,N-1),
A+B+C =:= N,
A + B > C,
A < B,
B <C,
A*A+B*B =:= C*C
].
problem9(N) ->
pythag(1000).
Cách trên cực kỳ kém hiệu quả, phải mất vài phút thì mới tìm ra.
Có một tính chất của Pythagorean triplet là
a = m2 − n2, b = 2mn, c = m2 + n2
m>n>0, and a
Viết lại với giải thuật trên.
algorithm, erlang, functionnal programming, projecteuler
17