Paul GrapeDrink Vagner Paul GrapeDrink Vagner - 4 months ago 12
Swift Question

How to write a function that multiplies 2 integers without using * operator

I am trying to figure out recursive operations.
I am trying to write a function that will multiply 2 integers without using the "*" operator.
I understand it has to be essentially

added to itself
number of times, but everything I find is either C, C++ or Java.

Something along the lines of:

var num1: Int
var num2: Int
var result: Int

func mult() -> Int {


Once again, I know it has to be something simple, however, I am probably over-complicating things (I tend to do that)


Give this a try (Swift 3):

func mult(x: Int, y: Int) -> Int {
    if x == 0 || y == 0 {
        return 0

    return x + mult(x: x, y: y - 1)

print(mult(x: 5, y: 10))

This only works if both x and y are greater than or equal to 0.