Search code examples
python-3.xdivide-by-zerobinomial-coefficients

Binomial coefficients - Division by zero error


The "main" code works to calculate every single binomial coefficient, unless (n = k + 1). It is mind boggling - it says there is a division by zero error but I cannot see why. the error occurs in the main function ( d = n2 / c ). Any idea why?

def getInteger( prompt ):
    while True:
        try:
            num = int( input(prompt))
        except ValueError:
            print( "That is not an integer -- please try again")
            continue
        return num   

def factorial(f):
    f = f
    q = (f - 1)
    fac = (f * q)
    while (q) > 1:
        q -= 1
        fac = (fac * q)
    return (fac)


def main():
    n = getInteger("enter a factor:")
    k = getInteger("enter a factor:")
    while n >= k :
        n2 = factorial(n)
        k2 = factorial(k)
        a = n - k
        b = factorial(a)
        c = b * k2
        d = n2 / c
        print("n2 = {} k2 = {} a = {} b = {} c = {} d = {}" .format(n2, k2, a, b, c, d)  )
        return
    else:
        print("n must be larger than k")

if __name__ == '__main__':
    main()    

main()

Note that I need to implement the calculations myself so I cannot use libraries.


Solution

  • Your factorial function is not correct for the inputs 0,1. It returns 0 for both of them, while it should return 1 for both of them.