Skip to content

Instantly share code, notes, and snippets.

@NathanKleekamp
Created September 6, 2019 19:05
Show Gist options
  • Save NathanKleekamp/e7f44f1f1d6f6734607ea0fb172f46a5 to your computer and use it in GitHub Desktop.
Save NathanKleekamp/e7f44f1f1d6f6734607ea0fb172f46a5 to your computer and use it in GitHub Desktop.
Adding together a sequence
// 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