Last active
November 7, 2018 13:58
-
-
Save illescasDaniel/c0b6f1a260d4b88f448b49fa623bfb40 to your computer and use it in GitHub Desktop.
Sum Range Swift
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
| extension ClosedRange where Bound: BinaryInteger { | |
| var sum: Bound { | |
| let uB = self.upperBound | |
| let lB = self.lowerBound | |
| return ((uB - (lB-1)) * (uB + lB)) / 2 | |
| } | |
| } | |
| extension Range where Bound: BinaryInteger { | |
| var sum: Bound { | |
| return (self.lowerBound...self.upperBound-1).sum | |
| } | |
| } | |
| assert((3...1234).sum == Array(3...1234).reduce(0,+)) | |
| assert((3..<1234).sum == Array(3..<1234).reduce(0,+)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment