Recursive function to fine a square of a number

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Something
    New Member
    • Nov 2011
    • 1

    Recursive function to fine a square of a number

    The idea is you input a number and a recursive function will return a square of the entered number.

    Example:

    Enter a number: 5
    Square of 5 is 25

    The input and display is all figured out, but I can't solve the recursive function itself. It gives me StackOverflow error at line 15, which is return (N * squareOf(N));

    Code:
    public static int squareOf(int N){
        if(N == 0){
            return 1;
        }else if(N == 1){
            return N;
        }else{
            return (N * squareOf(N));
        }
    }
  • rotaryfreak
    New Member
    • Oct 2008
    • 74

    #2
    the problem with the code you gave as an example, is that the value of N will never be 0 or 1 and because of this, your value of N is continuously growing until your machine runs out of room on the stack... hence the StackOverFlow exception.

    a closer look at the problem will actually show you how to solve it:
    in order to use recursion, you need to call the same function but gradually decreasing your value until it gets to zero. once it hits zero, you need to stop calling yourself and go back up the stack. Your first "if" statement should actually return 0, (this is what's called your base case), else call yourself with the value of n decremented.

    take a look at the mathematical operation you need to perform, which is n^2. We need to decrement the value of n in such a way that we can use it to call the same function but not change the mathematical formula so we get this:
    ==>(n-1)^2 and we know that this just really means
    ==>(n-1)(n-1)
    ==>(n^2 - 2n - 1)

    so we get that (n-1)^2 = (n^2 - 2n - 1). The laws of math say that we can rearrange this formula in a way such that we isolate the n^2 so by bringing everything to one side and isolating the n^2, we get this:

    n^2 = (n-1)^2 - 2n -1

    we now have our formula to iterate recursively though the square of a number:

    Code:
    public static int square(int n){
    		if(n == 0){
    	        return 0;
    	    }else{
    	        return ((square(n-1)+ (2*n)-1));
    	    }
    	}
    	public static void main(String[] args) {
    		System.out.println("The square of 5 is: " + SquareRoot.square(5));
    		
    	}
    }
    The program will produce the output:
    The square of 5 is: 25

    i would point out that recursion is great but if you try to iterate through the function too many times, you will eat the machine's resources, in that case, a for-loop or while-loop is probably the better choice.

    hope this helped

    Comment

    Working...