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
/** | |
Typical example of a recursive function taught at school. | |
But in practice implementing factorial recursively leads to a stackoverlow. And we can't use @tailrec for | |
n! = n * (n-1)! | |
BUT !! We don't really need recursion, do we?! | |
**/ | |
package numbers | |
object Numbers { | |
/** | |
1! = 1 | |
2! = 2 * 1! = 2 * 1 = 2 | |
3! = 3 * 2! = 3 * 2 = 6 | |
4! = 4 * 3! = 4 * 6 = 24 | |
5! = 5 * 4! = 5 * 24 = 120 | |
**/ | |
def factStackOverflow(num: Int): BigDecimal = { | |
if (num == 1) 1 | |
else num * factStackOverflow(num-1) | |
} | |
/** | |
1! = 1 | |
2! = 1! * 2 = 1 * 2 = 2 | |
3! = 2! * 3 = 2 * 3 = 6 | |
4! = 3! * 4 = 6 * 4 = 24 | |
5! = 4! * 5 = 24 * 5 = 120 | |
**/ | |
def factNonRecursive(num: Int): BigDecimal = { | |
(1 to num).map(x => BigDecimal.valueOf(x)).foldLeft(BigDecimal.valueOf(1)) ((a,b) => (a * b)) | |
} | |
} | |
/** | |
val x1 = Numbers.factNonRecursive(1) //> x1 : BigDecimal = 1.00 | |
val x2 = Numbers.factNonRecursive(10) //> x2 : BigDecimal = 3628800.00000000000 | |
val x3 = Numbers.factNonRecursive(10000) //> x3 : BigDecimal = 2.846259680917054518906413212119839E+35659 | |
val x4 = Numbers.factStackOverflow(1) //> x4 : BigDecimal = 1 | |
val x5 = Numbers.factStackOverflow(10) //> x5 : BigDecimal = 3628800 | |
val x6 = Numbers.factStackOverflow(10000) //> java.lang.StackOverflowError | |
//| at java.math.MathContext.equals(Unknown Source) | |
//| at scala.math.BigDecimal$.apply(BigDecimal.scala:61) | |
//| at scala.math.BigDecimal$.apply(BigDecimal.scala:59) | |
//| at scala.math.BigDecimal$.int2bigDecimal(BigDecimal.scala:146) | |
//| Output exceeds cutoff limit. | |
**/ | |
No comments:
Post a Comment