Java Square function

3.7k Views Asked by At

Would anyone be able to explain these methods with a few comments line. They are for squaring a number. One is using recursion, implementation and another is just normal

 public static int sq(int n)
{
    int i = 0 ;
    int result = 0 ;

    while(i < n){         
        result = result + 2*i + 1 ;
        i = i + 1 ;
    }
    return result ;
}

public static int recSq(int n)
{
    if(n == 0){
        return 0 ;
    } else {
        return recSq(n - 1) + 2*(n - 1) + 1 ;
    }
}

public static int implementSq(int n)
{
    int i ;
    int result = 0 ;

    for(i = 0 ; i < n ; i++){
        result = result + 2*i + 1 ;       
    }
    return result ;
} 
3

There are 3 best solutions below

0
Rubén On BEST ANSWER
  • The first one is multiplying the number by 2 n times using a loop to increase a local variable i.
  • The second one is doing exactly the same but using recursion. Each step decreasing n and returning 0 for the final case. All the calls are calling again to the same function with different parameters exept for the parameter value 0, then the function will return 0. Recursion is not a simple thing to think off, to understand it better try to imagine the codeflow.

Example: recSq(2)

  4 recSq(2)
  |<- 1  reqSq(1)+2*1+1
      |<-0  reqSq(0)+2*0 + 1
         |<-  0

reqSq(2) is called so we will eval the if and start evaluating the return statement. The first operation is a method call to reqSq(n-1) as n = 2 then we call to reqSq(1).

reqSq(1) is called so we will eval the if and start evaluating the return statement. The first operation is a method call to reqSq(n-1) as n = 1 then we call to reqSq(0).

reqSq(0) is called so we will eval the if, it's true cause n ==0 and then we return 0.

reqSq(1) call has finished evaluating reqSq(0) and then we can proceed calculating the rest 0 + 2*(n-1) + 1 -> 0 + 0 + 1. We will return the value 1.

reqSq(2) has finished evaluating reqSq(1) and then we can proceed calculating the rest 1 + 2*(n-1) +1 -> 1 + 2 + 1. We will return the value 4.

  • The last one is a for loop, practically the same as the first one but using fors instead of while loops. In a for loop you declare in one line the initialization condition, the continue condition and the increase operation. So in that case the for loop is starting with value 0, the loop will continue as i < n and at the end of the loop "i++" will be called.
2
Philipp Sander On

why are you trying to solve such a simple problem with recursion or loop?

public static int sq(int n) {
    return n * n;
}

that's it.

0
Richard Tingle On

I presume this must be a homework exercise, otherwise its an insane way to do anything. Therefore can I suggest using an integrated development environment (e. g. Netbeans) and then using it to step through the code line by line. This is by far the easiest way to understand what the code is doing. If we just tell you, you won't gain anything by it.