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.
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
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;
}
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();
}
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;
}
If you're just starting to learn Java programming, surprise your seniors with the correct answer.
Recommended Posts