Junior — Middle
How can one efficiently calculate the sum of numbers in the range from 1 to 1,000,000?
sobes.tech AI
Answer from AI
For efficient calculation of the sum of numbers from 1 to 1,000,000, it is better to use the arithmetic progression formula rather than summing the numbers in a loop. The formula:
[ S = \frac{n \times (n + 1)}{2} ]
where n = 1,000,000.
Example in Kotlin:
val n = 1_000_000L
val sum = n * (n + 1) / 2
println("Sum from 1 to $n is $sum")
This approach works in constant time and does not require significant resources.