user14837934
user14837934

Reputation:

Multiplication in Java using recursion

I am new to programming and I am writing a simple code in Java that is using recursion. I want to show the product of two numbers (from start to End). The return of the method is the multiplication of the numbers from start to end. (For Example: If the numbers are 1 and 3 then I want the method to return 6. I managed to do the recursion but I am not sure if the code is effective at all. Here is my code so far. Thanks

public class ÜbungsblattSieben {
    public static void main(String[] args) {
        System.out.println(multiplyFromStartToEnd(1, 3));
    }

    public static int multiplyFromStartToEnd(int start, int end) {
        if (start == end) {
            return end;
        } else {
            return start * multiplyFromStartToEnd(++start, end);
        }
    }
}

Upvotes: 2

Views: 202

Answers (1)

Zabuzard
Zabuzard

Reputation: 25943

Your code is as effective as a recursive multiplication can be. Well done.

That said, here are a few notes:

  • You may write start + 1 instead of ++start. Generally easier to read and understand. Also you do not have to change the start variable itself, you just want to pass a bigger number to the method call, thats all.

  • You may also want to properly indent your code (just hit the auto-format key in your IDE).

  • I would also suggest to rename your method to multiplyFromTo, but thats a very subjective note.

All in all, your code would then look like:

public class ÜbungsblattSieben {
    public static void main (String[] args) {
        System.out.println(multiplyFromStartToEnd(1, 3));
    }

    public static int multiplyFromTo(int start, int end) {
        if (start == end) {
            return end;
        } else {
            return start * multiplyFromStartToEnd(start + 1, end);
        }
    }
}

For reference, here is how an iterative version could look like:

int result = 1;
for (int i = start; i <= end; i++) {
    result *= i;
}
System.out.println(result);

Obviously, this is a lot faster than recursion.

Upvotes: 2

Related Questions