HiveBrain v1.2.0
Get Started
← Back to all entries
debugMinor

Pascal triangle algorithm is good but fails

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
failspascalbuttrianglealgorithmgood

Problem

I have created a function which returns the number that corresponds to the given row and column from the pascal triangle. I have used the formula for this:


n! / r! * (r-n)!

The code:

def pascal(c: Int, r: Int): Int = {

    def factorial(number: Int): Int = {

      def loop(adder: Int, num: Int): Int = {
        if( num == 0) adder
        else loop(adder * num, num - 1)

      }

      loop(1,number)
    }

    factorial(r) / (factorial(c) * factorial(r-c));
}


I received 180 points out of 190 for this function because it returns an arithmetic exception for a given case (they don't give me the case). How could I improve this code and how can I make it better? Most importantly, how can I spot the bug?

Solution

The code appears to be correct, though the explanatory formula you posted is wrong.

Your factorial function is more complex than it needs to be. Furthermore, adder is a poor variable name, since the result is multiplicative rather than additive. The traditional recursive definition is:

def factorial(n: Int): Int = {
    if (n == 0) 1
    else n * factorial(n - 1)
}


The main problem with your approach is that you work with large numbers in both the numerator and the denominator. If your program is generally working, then your problem is probably arithmetic overflow. An Int would only handle values up to 231 - 1 correctly.

Therefore, your best bet is to use an entirely different way to construct Pascal's Triangle, as suggested by @janos.

Code Snippets

def factorial(n: Int): Int = {
    if (n == 0) 1
    else n * factorial(n - 1)
}

Context

StackExchange Code Review Q#49268, answer score: 5

Revisions (0)

No revisions yet.