If there is any way to call a def from a block
def factor (n: Int) : Int = if (n == 0 ) 1 else n * factor(n-1)
val i = 1000
i.toString.foreach ( x => sum += factor(x.toInt) )
at the end I want to get the sum of factorial of every digit
But it seems like def doesn’t return a value, everytime is 0
How to fix it?
Thanks!
The problem actually has nothing to do with Scala per se; your code and your
defare fine. The issue is withtoInt:toIntdoesn’t actually convert it as a decimal digit, but as a unicode (ish?) character value. These are producing very large numbers which go beyond whatfactorcan handle:So instead use (thanks to Luigi)