May
May

Reputation: 131

Java - Calculating the sum of all even numbers up to a certain number

How do I calculate the sum of all the even numbers up to a certain number entered by the user using Java?

Upvotes: 0

Views: 1899

Answers (2)

ForeverStudent
ForeverStudent

Reputation: 2537

The naive solution would be to start from 0 and keep adding even numbers like this:

public static int square (int x)
{
    int sum= 0;
    for(int i = 0; i <= x; i+=2) sum += i;
    return sum;
}

but you don't have to do this. This is a simple arithmetic sequence and to calculate the sum you can use the formula sum= n(a1 + an)/2 where a1 is the first term, 'an' is the last term and n is the total number of terms in the sequence.

for you a1 is 2, an is the parameter and you can calculate n by dividing the parameter (rounded down to closest even number) by 2.

This way your function will be:

public static int square (int x)
{   
    //you can do error checking if you want, x has to be non negative

    if( (x%2) !=0) x--;

    //x is guaranteed to be even at this point so x/2 is also an int
    int sum= x/2 *(1+x/2);

    return sum;
}

Upvotes: 2

Kevin Mee
Kevin Mee

Reputation: 549

The trick to this question is "even numbers". By using % (the modulus operator) you can find these numbers easy. If you are curious about Mod, check this link https://msdn.microsoft.com/en-us/library/h6zfzfy7(v=vs.90).aspx

Using the square method you currently have and making a few modifications you can achieve the solution.

static int square (int x)
{
    int result = x;

    for(int i = 0; i < x; i++){
         if(i%2 == 0){
             result += i
         }   
    }

    return result;
}

Upvotes: 1

Related Questions