简体   繁体   中英

array, integers and sum of array

Problem: Write a method that takes two integers n and m as parameters, and return the sum of alle the numbers (array of numbers) from n (including n) to m (including m).

public int getSum(int n, int m){
    this.n = n;
    this.m = m;
    int [] x = {n,m};
    int result = 0;
    for(int i=0; i<x.length; i++){
        result += x[i];
    }
    return result;
}

if n=1 and m=4 the method returns 5, but the method need to return 10, (1,2,3,4)=(1+2+3+4). Guess this line is not right int [] x = {n,m}; since the array will be {1,4} if n=1 and m=4. How to fix this, need to create the array {1,2,3,4} if n=1 and m=4

try this:

public int getSum(int n, int m){
    int result = 0;
    for(int i = n;i <= m;i++)
         result += i;
    return result;
}

or this:

public int getSum(int n, int m){
    int result = 0;
    while(n <= m)
         result += n++;

    return result;
}

or maybe with funny math:

public int getSum(int n, int m){
    return (m*(m+1)/2) - ((n-1)*((n-1)+1)/2)
}

F(n) = (n*(n+1)/2) = 0+1+2+...+n
F(m) - F(n-1) = n + n+1 + n+2 + ... + m

Java 8

return IntStream.rangeClosed(n, m).sum();

@Andres has already given a perfect solution. But I wanted to explain some more, so here goes.

There are many problems with your code.

But yes, the central problem is the line. int [] x = {n,m};

What that line does is creates an array of just 2 numbers, and when you iterate over that array you are only adding those two numbers, not all the number in between.

In languages like C, C++, Java, etc... the simplest idiom to iterate over a range of numbers is

for(int i = n, i <=m, i++){
  ...
}

What this does is, create a temporary variable i and initialize it to the first number in the range n . And then run in the loop incrementing that temporary number i by one every time until it exceeds the last number of the range m .

Within the body of the loop each number of the range will now be available, for that iteration of the loop.

So in your case where you are summing up all the numbers, you can accumulate all those numbers in the range by setting up an accumulator variable like following.

int acc = 0;
for(int i = n, i <=m, i++){
  acc = acc + i;
}

can't you just do this :

public static int getSum(final int n, final int m) {
    // default value
    int sum = 0;

    // not permitted
    if (n >= m)
        return 0;

    // all of the work here
    for (int i = n; i <= m; i++)
        sum += i;

    return sum;
}

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