Skip to content

Instantly share code, notes, and snippets.

@swift-student
Last active February 12, 2020 16:51
Show Gist options
  • Save swift-student/74ea1ac453e303b18678e5b53e1f1188 to your computer and use it in GitHub Desktop.
Save swift-student/74ea1ac453e303b18678e5b53e1f1188 to your computer and use it in GitHub Desktop.

Since I am writing a function that takes two positive integers, it would be wise to guard against negative values. After that, I think I would iterate through all possible cominations of numbers that would add up to the sum, and try multiplying them to see if they equal the product. I should divide the sum by two so that I start at the smallest integers before working my way outward, as the instructions are asking for the two smallest positive integers. I would then return an array with the two numbers, with the smaller one preceeding the larger one. This may likely be a very naive solution and may be quite inneficient with some input cases, but it should work.

func sumAndProduct(_ sum: Int, _ product: Int) -> [Int] {
    // First off, let's guard against non-positive integers
    guard sum > 0, product > 0 else { return [] }
    
    // If the sum is odd, dividing by 2 will result in x rounding down
    var x = sum / 2
    // So then we will take the sum and subtract x to get y
    var y = sum - x
    
    // We now have our two smallest integers that add up to the sum
    // Next, let's loop through all possible combinations while x is still greater than 0 and y is less than the sum
    // We could just check y, since it should be closer to the sum than x is to 0 if anything, but I'll check both
    while x > 0, y < sum {
        // If x times y equals the product, we have our smallest two integers, and can return them
        if x * y == product {
            return [x,y]
        } else {
            // If not we will decrement x (because it comes first and should be smaller) and increment y
            x -= 1
            y += 1
        }
    }
    
    // If we exit our while loop without finding a solution, we return an empty array
    return []
}

This challenge tripped me up at first until I read it for a bit and fully understood what they were looking for. It seemed more intimidating than it ended up being. Walking through the problem and describing what the expected results were made me realize that I needed to divide the sum by two to come up with the two smallest possible integers and work my way outward from there, testing if when multiplied they produced the product given. Also, I wrote out a test case with pencil and paper to help my mind think through the solution in a different medium.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment