开发者

Better way of calculating sum of even ints

开发者 https://www.devze.com 2023-03-09 16:10 出处:网络
I\'m trying to write a programme to prompt the user to input an int which is above or equal 2. From this input the programme must then 开发者_高级运维calculate and print the sum of all the even intege

I'm trying to write a programme to prompt the user to input an int which is above or equal 2. From this input the programme must then 开发者_高级运维calculate and print the sum of all the even integers between 2 and the entered int. It must also produce an error message if the inputted int is below 2. I've made a programme for it that works but am just wondering if you guys could find a better way of doing it? I'm sure there is but I can't quite seem to find a way that works!

Here's what I did:

import java.util.Scanner;

public class EvenSum {


         public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);

    System.out.println("Enter an integer which is above 2.");
    int number = scan.nextInt();
    int divnum = number / 2;
    int divnum2 = divnum + 1;
    int sumofeven = divnum * divnum2;

    if(number >= 2)
    System.out.println("The sum of the even integers between the number is "+
            sumofeven);
    else
        System.out.println("Invalid number entered.");


    }

}


Note: do not use this example in a real context, it's not effective. It just shows a more clean way of doing it.

    // Check the input.
    if (number >= 2)
        System.out.println(sum(number));
} 

// Will find the sum if the number is greater than 2.
int sum(int n) {
    return n == 2 ? n - 2 : n % 2 == 0 ? n + sum(n - 2) : sum(n - 1);
}

Hope this helps. Oh, by the way, the method sum adds the numbers recursively.

Sorry, but I had to edit the answer a bit. There might still be room for improvement.


Why do it with a loop? You can actually calculate it out. Let X be the number they choose. Let N be the largest even number <= X. (N^2+2*N)/4 will be your answer.

Edit: just saw the answer above me. He is right. I gave the function I suppose.


Why use a loop at all? You are computing the sum of:

2 + 4 + ... n, where n is a positive even number.

This is a very simple arithmetic progression.


public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);

    System.out.println("Enter an integer which is above 2.");

    int number = scan.nextInt();

    if (number >= 2) {
        int sumofeven = 0;
        for (int i = 2; i <= number; i += 2) {
            sumofeven += i;
        }
        System.out.println("The sum of the even integers between the number is " + sumofeven);
    } else {
        System.out.println("Invalid number entered.");
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消