The correct answer for money! The correct answer for silver! [Japanese version of sequence]

If you've started learning programming, you've probably written a program that asks for the sum of sequences. When writing a program that asks for the sum of a sequence in a Java program, the result is different depending on the person, so I summarized it like a quiz program on Fuji TV.

problem

Create a method that takes two integers a and b as arguments and returns the sum of the integers from a to b. However, the arguments are subject to the following conditions.

--a <b --a> = 0 --b <100000

Iron correct answer

Implementation using the standard for statement. Most people do this, and of course I too. I'm writing this unknowingly. However, this has a lot of code and is slow.

int iron (int a, int b) {
	int result = 0;
	for (int i = a; i <= b; i++) {
		result = result + i;
	}
	return result;
}

Silver correct answer

Implement smartly using convenient functions introduced from Java 8. Those who are sensitive to new technologies will write this.

int silver (int a, int b) {
	return IntStream.range(a, b + 1).sum();
}

Gold correct answer

Bring up [Arithmetic progression sum formula](https://ja.wikipedia.org/wiki/ Arithmetic progression). The wise guy writes this, unbelievable. (Adopted the function of saka1029 in the comment section)

int gold (int a, int b) {
	return (a + b) * (b - a + 1) / 2;
}

Finally

If you're just starting to learn Java programming, surprise your seniors with the correct answer.

Recommended Posts

The correct answer for money! The correct answer for silver! [Japanese version of sequence]
Links for each version (Japanese version) of Java SE API
Switch the version of bundler
[Java version] The story of serialization
Check the version of Cent OS
About the version of Docker's Node.js image
Correct the stop position of smoothScrollToPosition of RecyclerView
[Japanese version Faker] About the gem "gimei"
Check the version of the standard Web software.