compiler: closed-form Enum.sum for stepped ranges (O(1) vs O(n))#115
Merged
compiler: closed-form Enum.sum for stepped ranges (O(1) vs O(n))#115
Conversation
Use the arithmetic progression formula S = n*(first+last)/2 for Enum.sum(start..stop//step) when step is a constant integer. Previously, non-unit step ranges fell back to an O(n) reduce loop. Now all constant-step ranges use the O(1) closed-form formula: count = max(div(stop - start, step) + 1, 0) last = start + (count - 1) * step sum = count * (start + last) / 2 Examples: Enum.sum(1..9//2) # 1+3+5+7+9 = 25 (was loop, now O(1)) Enum.sum(0..12//3) # 0+3+6+9+12 = 30 (was loop, now O(1)) The integer division by 2 is exact because for any arithmetic progression, either count or (first+last) is always even. Non-constant step expressions still fall back to reduce loops.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Use the arithmetic progression formula
S = n*(first+last)/2forEnum.sum(start..stop//step)when step is a constant integer.Problem
Previously,
Enum.sum(start..stop//step)with non-unit step fell back to an O(n) reduce loop, generating a helper function and iterating over every element.Solution
Apply the closed-form arithmetic progression formula for all constant-step ranges:
This computes the result in O(1) — no loop, no helper function.
Examples
Enum.sum(1..9//2)→ 1+3+5+7+9 = 25 (was O(n) loop, now O(1))Enum.sum(0..12//3)→ 0+3+6+9+12 = 30 (was O(n) loop, now O(1))Correctness
The integer division by 2 is exact because for any arithmetic progression, either the count or (first+last) is always even.
What's unchanged
Enum.sum(start..stop)(step=1) still uses its existing closed-formTests