Created
September 6, 2019 19:05
-
-
Save NathanKleekamp/e7f44f1f1d6f6734607ea0fb172f46a5 to your computer and use it in GitHub Desktop.
Adding together a sequence
This file contains 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
// With a loop O(n) | |
const sumSequenceLoop = (seq) => seq.reduce((accum, current) => accum + current); | |
console.log(sumSequenceLoop([1, 2, 3, 4])) // 10 | |
console.log(sumSequenceLoop([2, 4, 6])) // 12 | |
console.log(sumSequenceLoop([3, 6, 9, 12])); // 30 | |
// With Gauss's formula O(1) | |
const sumSequence = (seq) => seq.length * (seq[0] + seq[seq.length - 1]) / 2; | |
console.log(sumSequence([1, 2, 3, 4])) // 10 | |
console.log(sumSequence([2, 4, 6])) // 12 | |
console.log(sumSequence([3, 6, 9, 12])); // 30 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment