[erlang-questions] is this a well written function

Robert Wilkinson bob@REDACTED
Mon Feb 9 16:22:35 CET 2015

```On Mon, Feb 09, 2015 at 03:38:10PM +0100, Roelof Wobben wrote:
> I know , the exercise is stated this :
>
> Write a function sum/1which, given a positive integer N, will return
> the sum of all the
> integers between 1 and N.
>
> Roelof

If that is the problem, then the most effective way is to sum the
Arithmetic progression?

n * (n + 1) / 2 is the sum of an AP (IIRC).

so

sum(N) -> (((N + 1) * N) / 2) .

which will be much faster than recursion ?

Bob

> Martin Koroudjiev schreef op 9-2-2015 om 15:32:
> >It's perfect, just note that you will get "no function clause" exception
> >if you pass negative number to the function which is probably desired
> >result.
> >
> >Martin
> >
> >On 2/9/2015 4:11 PM, Roelof Wobben wrote:
> >>Roelof Wobben schreef op 9-2-2015 om 14:39:
> >>>sum(End) -> sum_acc(0, 0, End).
> >>>
> >>>sum_acc(Acc, _, 0) ->
> >>>      Acc;
> >>>sum_acc(Acc, Current, Rem) ->
> >>>      sum_acc(Acc + Current, Current + 1, Rem - 1).
> >>
> >>A new try after some remarks :
> >>
> >>-module(sum_recursion).
> >>
> >>-export([sum/1]).
> >>
> >>% when the number is zero the outcome will also be zero
> >>sum(0) ->
> >>   0;
> >>
> >>% when a number is greater then 0 , call the helper function.
> >>sum(End) when End > 0 ->
> >>   sum_acc(0, End).
> >>
> >>% When End is equal to zero all the numbers are added
> >>sum_acc(Acc, 0) ->
> >>      Acc;
> >>
> >>% when end is not zero there are more numbers to be added.
> >>sum_acc(Acc, End) ->
> >>      sum_acc(Acc + End, End - 1).
> >>
> >>Roelof
> >>_______________________________________________
> >>erlang-questions mailing list
> >>erlang-questions@REDACTED
> >>http://erlang.org/mailman/listinfo/erlang-questions
> >_______________________________________________
> >erlang-questions mailing list
> >erlang-questions@REDACTED
> >http://erlang.org/mailman/listinfo/erlang-questions
> >
>
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions

```