Skip to content

Commit

Permalink
factorial iterative & recursive (TheAlgorithms#39)
Browse files Browse the repository at this point in the history
  • Loading branch information
ashwani-rathee committed Jun 14, 2021
1 parent 229d749 commit fcf36a9
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/TheAlgorithms.jl
Expand Up @@ -32,6 +32,8 @@ export area_triangle
export ceil_val, floor_val
export collatz_sequence
export euler_method
export factorial_iterative
export factorial_recursive
export is_armstrong
export line_length
export mean
Expand Down Expand Up @@ -86,6 +88,7 @@ include("math/average_mode.jl")
include("math/ceil_floor.jl")
include("math/collatz_sequence.jl")
include("math/euler_method.jl")
include("math/factorial.jl")
include("math/line_length.jl")
include("math/perfect_cube.jl")
include("math/perfect_number.jl")
Expand Down
52 changes: 52 additions & 0 deletions src/math/factorial.jl
@@ -0,0 +1,52 @@
"""
factorial_iterative(n)
Finds factorial of a number using Iterative method
# Example
```julia
factorial_iterative(5) # returns 120
factorial_iterative(0.1) # returns error
factorial_iterative(-1) # returns error
```
# Reference
- factorial of a positive integer -- https://en.wikipedia.org/wiki/Factorial
Contributed By:- [Ashwani Rathee](https://github.com/ashwani-rathee)
"""
function factorial_iterative(n)
if n != trunc(n) || n < 0
throw(error("factorial_iterative() only accepts non-negative integral values"))
end
factorial::BigInt = 1
map(i -> factorial *= i, 1:n)
return factorial
end

"""
factorial_recursive(n)
Finds factorial of anumber using recursive method
# Example
```julia
factorial_recursive(5) # returns 120
factorial_recursive(0.1) # returns error
factorial_recursive(-1) # returns error
```
# Reference
- factorial of a positive integer -- https://en.wikipedia.org/wiki/Factorial
Contributed By:- [Ashwani Rathee](https://github.com/ashwani-rathee)
"""
function factorial_recursive(n)
if n != trunc(n) || n < 0
throw(error("factorial_iterative() only accepts non-negative integral values"))
end
if n == 0 || n == 1
return 1
else
factorial::BigInt = n * factorial_recursive(n - 1)
return factorial
end
end
10 changes: 10 additions & 0 deletions test/math.jl
Expand Up @@ -129,6 +129,16 @@ end
@test euler_method((x, t) -> x, 1, (0, 5))[1][end] == 143.33937864611195
end

@testset "Math: Factorial Related" begin
@test factorial_iterative(5) == 120
@test_throws ErrorException factorial_iterative(0.1)
@test_throws ErrorException factorial_iterative(-1)

@test factorial_recursive(5) == 120
@test_throws ErrorException factorial_recursive(0.1)
@test_throws ErrorException factorial_recursive(-1)
end

@testset "Math: Line Length" begin
# Arc Lengths
@test line_length(x -> x, 0, 1, 10) == 1.4142135623730947
Expand Down

0 comments on commit fcf36a9

Please sign in to comment.