Thursday 9 February 2017

factorial of a number using erlang


Factorial of a non negative Number in math represented as n!.
for example:-
5!= 5x4x3x2x1=120


-module(my_math).
-export([factorial/1]).

factorial(Num) when is_integer(Num) and (Num >= 0) ->
        factorial(Num, 1).
factorial(0, Res)->
        Res;
factorial(Num, Res)->
        factorial(Num -1, Num*Res).

Compile and Run


rajesh@ideapad:~/Rajesh/Blog/factorial$ erl
Erlang/OTP 18 [erts-7.3] [source] [64-bit] [smp:4:4] [async-threads:10] [kernel-poll:false]

Eshell V7.3  (abort with ^G)
1> c(my_math).
{ok,my_math}
2> my_math:factorial(5).
120
3> my_math:factorial(0).
1
4> my_math:factorial(1).
1
5> my_math:factorial(10).
3628800
6> 

1 comment:

  1. factorial hundred In the last few days, the “factorial of 100” is one of the top subjects and a lot of maths geeks compute it using voice assistants such as Alexa, Shiri, etc.
    factorial hundred In the last few days, the “factorial of 100” is one of the top subjects and a lot of maths geeks compute it using voice assistants such as Alexa, Shiri, etc.

    ReplyDelete