简体   繁体   中英

Calculating sum 1 to N by adding 1 to N/2 with N/2 to N in a recursive method

I am having trouble making a recursive method that calculates the sum of 1,2,3 to N, but does it by adding (1,2,3... to N/2) with (N/2+1... to N).

The code i manage so far is this:

public static void main(String[] args) {

    System.out.println(sum(10, 1));
}

public static int sum(int n, int start) {

    if (start == n){
        return n;
    }

    if (start > n / 2){
        return start + sum(n, start + 1);
    }

    return start + sum(n, start + 1);

}

I believe this is wrong, It is an assignment in school where we have to motivate how splitting the recursion up into to parts is a more/lesser efficient way of calculating the sum. (adding numbers from 1 to N/2 with N/2 to N, instead of just from 1 to N directly).

He made us do this way to make it harder for us but i cannot grasp the idea on how to do this at all. Is it correct?

Thanks

Might be helpful in some cases to reduce recursion depth.

You need to take start into account when calculating n/2 for inner steps, the code should probably look similar to this:

public static int sum(int n, int start) {
  if (start > n) {
    return 0;
  }

  if (start == n){
      return n;
  }

  int n2 = (start + n) / 2;
  return sum(n2, start) + sum(n, n2 + 1);
} 

The start > n check just avoids extra checks at the end for the case where start and n are less than 2 apart.

I believe, that this piece of code is as simple as possible, you can check performance in a loop. I don't see any difference in complexity.

class Sums {

    public static int sumHelp(int n, int start){
        if (n == start) return;
        else return (n + sumHelp(n - 1, start));
    }

    public static int sumByHalf(int n){
        return sumHelp(n/2, 0) + sumHelp(n, n/2);
    }

    public static int sum(int n){
        return sumHelp(n, 0);
    }

    public static void main(String[] args) {
        System.out.println(sumByHalf(100));
        System.out.println(sum(100));
    }
}    

Check out that you got declare n as an int. n/2 not always will give to you the expected value. I think that's the trick your teacher wants you to observe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM