Shorter code

This commit is contained in:
Dan Ballard 2011-04-01 12:34:24 -07:00
parent ee9765dbac
commit 76458d1f0a
6 changed files with 12 additions and 29 deletions

13
e1.erl
View File

@ -1,13 +1,8 @@
-module(e1).
-export([e1/0]).
add_list([], Acc) -> Acc;
add_list([X| Tail], Acc) -> add_list(Tail, Acc+X).
sum_divisors(Max, Max, Acc) -> Acc;
sum_divisors(Start, Max, Acc) when Start rem 3 == 0; Start rem 5 == 0 -> sum_divisors(Start+1, Max, Acc+Start);
sum_divisors(Start, Max, Acc) -> sum_divisors(Start+1, Max, Acc).
find_3_5_divisibles(Start, Max) -> find_3_5_divisibles(Start, Max, []).
find_3_5_divisibles(Max, Max, Acc) -> Acc;
find_3_5_divisibles(Start, Max, Acc) when Start rem 3 == 0; Start rem 5 == 0 -> find_3_5_divisibles(Start+1, Max, [Start |Acc]);
find_3_5_divisibles(Start, Max, Acc) -> find_3_5_divisibles(Start+1, Max, Acc).
e1() -> add_list(find_3_5_divisibles(2, 1000), 0).
e1() -> sum_divisors(2, 1000, 0).

3
e1.m
View File

@ -1,8 +1,5 @@
// comment
#include <objc/Object.h>
int main(int argc, char **argv) {
int sum = 0;
int i;

16
e1.pl
View File

@ -1,13 +1,7 @@
range(End, End, []) .
range(Start, End, [Start| Acc]) :- Next is Start + 1, range(Next, End, Acc).
divisible_3_5(N) :- 0 is N rem 3 ; 0 is N rem 5.
divisors_3_5([], []).
divisors_3_5([X|Xs], [X|Ys]) :- 0 is X rem 3, divisors_3_5(Xs, Ys).
divisors_3_5([X|Xs], [X|Ys]) :- 0 is X rem 5, divisors_3_5(Xs, Ys).
divisors_3_5([X|Xs], Ys) :- divisors_3_5(Xs, Ys).
sum_divisors(End, End, Total, Total).
sum_divisors(Start, End, Acc, Total) :- divisible_3_5(Start), Next is Start + 1, NewAcc is Acc + Start, sum_divisors(Next, End, NewAcc, Total).
sum_divisors(Start, End, Acc, Total) :- Next is Start + 1, sum_divisors(Next, End, Acc, Total).
sum(List, Result) :- sum(List, 0, Result).
sum([], Acc, Acc).
sum([X|Xs], Acc, Num) :- Inc is X + Acc, sum(Xs, Inc, Num).
e1(Result) :- range(1,1000, R), divisors_3_5(R, Ds), sum(Ds,Result).
e1(Result) :- sum_divisors(2, 1000, 0, Result).

1
e1.py
View File

@ -4,5 +4,4 @@ sum = 0
for i in range(2,1000):
if i % 3 == 0 or i % 5 ==0 :
sum += i
print sum

4
e1.rb
View File

@ -1,11 +1,9 @@
#!/usr/bin/ruby
sum = 0
for i in 2..999
if i % 3 == 0 or i % 5 == 0
sum += i
end
end
print sum.to_s + "\n"
puts sum

View File

@ -1,3 +1,3 @@
erl
c(filename)
module:function
c(filename).
module:function().