Skip to content

Instantly share code, notes, and snippets.

@SergeyTLV
Last active October 1, 2020 16:36
Show Gist options
  • Save SergeyTLV/9bb88a15c04af3e1db08e14f64275b75 to your computer and use it in GitHub Desktop.
Save SergeyTLV/9bb88a15c04af3e1db08e14f64275b75 to your computer and use it in GitHub Desktop.
/* Given the triangle of consecutive odd numbers:
1
3 5
7 9 11
13 15 17 19
21 23 25 27 29
...
Calculate the row sums of this triangle from the row index (starting at index 1) e.g.:
rowSumOddNumbers(1) // 1
rowSumOddNumbers(2) // 3 + 5 = 8
*/
func rowSumOddNumbers(_ row: Int) -> Int {
var x = 1 + (row - 1) * row
var y = x + (row - 1) * 2 + 1
return stride(from: x, to: y, by: 2).reduce(0, +)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment