-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Includes recursive factorial challenge
- Loading branch information
Showing
3 changed files
with
63 additions
and
0 deletions.
There are no files selected for viewing
61 changes: 61 additions & 0 deletions
61
Challenges2022.playground/Pages/Challenge#13.xcplaygroundpage/Contents.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
/*: | ||
| ||
[< Previous](@previous) [Home](Introduction) [Next >](@next) | ||
# Challenge 13: Recursive factorial | ||
Write a function which calculates and returns factorial of a given number in a recursive way. | ||
*/ | ||
import Foundation | ||
|
||
func recursiveFactorial(number: Int) -> Int? { | ||
(number <= 0) ? nil : (number <= 1) ? 1 : number * (recursiveFactorial(number: number - 1)!) | ||
} | ||
|
||
func unwrapRecursiveFactorial(number: Int) -> String { | ||
guard let result = recursiveFactorial(number: number) else { | ||
return "No tiene factorial" | ||
} | ||
return String(result) | ||
} | ||
|
||
|
||
print(""" | ||
Test 1, factorial de 0: | ||
\(unwrapRecursiveFactorial(number: 0)) | ||
""") | ||
|
||
print(""" | ||
Test 2, factorial de 7: | ||
\(unwrapRecursiveFactorial(number: 7)) | ||
""") | ||
|
||
print(""" | ||
Test 3, factorial de 10: | ||
\(unwrapRecursiveFactorial(number: 10)) | ||
""") | ||
|
||
print(""" | ||
Test 4, factorial de 1: | ||
\(unwrapRecursiveFactorial(number: 1)) | ||
""") | ||
|
||
print(""" | ||
Test 5, factorial de -1: | ||
\(unwrapRecursiveFactorial(number: -1)) | ||
""") | ||
|
||
print(""" | ||
Test 6, factorial de 4: | ||
\(unwrapRecursiveFactorial(number: 4)) | ||
""") | ||
|
||
//: [Next](@next) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters