Recursion is driving me crazy!!!!!!!!!!!!! - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

Recursion is driving me crazy!!!!!!!!!!!!!

joker2ujoker2u Posts: 5Member
I am trying to learn recursion right now and I am having a very difficult time...

I am trying to multiply 2 integers recursively.

This code works as long as int y doesn't exceed 6202, otherwise I am getting a stack overflow error.

public static int multiply(int x, int y){
int result = 0;
if(x == 0 || y == 0){
result = 0;
}
else if(x == 1){
result = y;
}
else if(y == 1){
result = x;
}
else{
result = x + multiply(x, y - 1);
}
return result;
}

I am trying to write a method that uses the modular (%) function to break down x and y into their individual numbers i.e.
startMod = 10;
567
X863
----
3 * (7 * (startMod / 10) +
3 * (6 * (startMod) +
3 * (5 * (startMod) +
6 * (startMod) ( 7 * (startMod / 10)) +
6 * (startMod) ( 6 * (startMod)) +
6 * (startMod) ( 5 * (startMod)) +
8 * (startMod * 10) ( 7 * (startMod / 10)) +
8 * (startMod * 10) ( 6 * (startMod)) +
8 * (startMod * 10) ( 5 * (startMod)) == 567 * 863

This would be the recursion part of it I assume but I have worked on this for about 12 hours and can't seem to code anything that works.

It is essentially elementary multiplication.
54
X27
---
7 * 4 + 7 * 50 + 20 * 4 + 20 * 50 == 54 * 27

Any amount of help with this problem would be greatly appreciated.

Thank you
Joker2u

Comments

  • incodedincoded Posts: 1Member
    [link=http://pages.cs.wisc.edu/~vernon/cs367/notes/6.RECURSION.html]][/link] is a decent site to look over and it is in Java. Recursion means that you have a base case/a way to exit, usually in an if statement to check to see if the program needs to go any farther. Then inside the method, you make a call to that method. Such as:

    [code]int factorial (int N) {
    if (N == 0) return 1; //base case
    else return (N*factorial(N-1));//recursion call[/code]

    This calls the function "recursively" and where N,(N - 1) for 1 less call the next time factorial is called. So each time the method is called by itself, it subtracts 1 getting closer to what the function is trying to do/find.(respectively) Give this site a "once-over" and see if it makes more sense. Hope I have shed some light.
Sign In or Register to comment.