Home > OS >  This program is stack overflowing and I am not sure why
This program is stack overflowing and I am not sure why

Time:04-03

I had to write the following for a programming assignment and after running the code and giving input from the user it overflows.

package main

import (
    "fmt"
)

func hypercake(n int, k int) int {
    combinations := func(n int, r int) int {
        var factorial func(int) int
        factorial = func(n int) int {
            if n < 0 {
                fmt.Print("Cannot take the factorial of a negative number.")
                return -1
            } else if n == 0 {
                return 1
            } else {
                return factorial(n) * factorial(n-1)
            }
        }

        if r >= 0 && r <= n {
            ans := factorial(n) / (factorial(r) * factorial(n-r))
            return ans
        } else {
            fmt.Print("Something was wrong with input")
            return -1
        }
    }

    sum := 0
    if k > 0 {
        if k == 1 {
            return 1
        } else {
            for i := 0; i <= k; i   {
                sum  = combinations(n, i)
            }
        }
        return sum
    } else {
        fmt.Print("You must have a postive number of dimensions")
        return -1
    }
}

func main() {
    var n, k int
    fmt.Print("Type how many cuts in your cake.")
    fmt.Scan(&n)
    fmt.Print("Type how many dimensions in your cake.")
    fmt.Scan(&k)
    ans := hypercake(n, k)
    fmt.Print(ans)
}

I have tried using very small inputs because I thought that it was just exceeding the bounds for a n int and that did not work.

CodePudding user response:

It seems to me that you don't understand factorial. Consider n! = n * (n - 1) * (n - 2) ... you get the idea. It is f(n) = n * f(n - 1)

But you implement factorial as: f(n) = f(n) * f(n - 1) You ultimately end up calling the same function with the same arguments you've taken - hence the stack overflow.

I would recomend that you change

return factorial(n) * factorial(n-1)

to

return n * factorial(n-1)

Hope this helps!

  •  Tags:  
  • go
  • Related