DEV Community

Discussion on: Daily Challenge #55 - Building a Pile of Cubes

Collapse
 
dak425 profile image
Donald Feury

Here is a loop based solution, I'm sure there is a formula for finding it but I don't have time right now to figure it out or Go find it.

cubes.go

package cube

// Cubes will determine the count of cubes necessary as n to construct a pile of volume m
// If no amount can equal m, 0 is returned
func Cubes(m int) int {
    var n, total int

    for total < m {
        n++
        total += (n * n * n)
    }

    if total == m {
        return n
    }

    return 0
}

cubes_test.go

package cube

import (
    "testing"
)

var testCases = []struct {
    description string
    input       int
    expected    int
}{
    {
        "challenge example 1",
        1071225,
        45,
    },
    {
        "challenge example 2",
        91716553919377,
        0,
    },
}

func TestCubes(t *testing.T) {
    for _, test := range testCases {
        if result := Cubes(test.input); result != test.expected {
            t.Fatalf("FAIL: %s - Cubes(%d): %d, expected %d", test.description, test.input, result, test.expected)
        }
        t.Logf("PASS: %s", test.description)
    }
}