
Coding Interview Question:
Write a function sum(a)(b)(c)...( n)() , which returns the sum of a+b+c...+n
One line solutions (in Javascript):
1. If a,b,c...n are consecutive integers starting from 1 or 0 then the answer is:
const sum = a => a*(a+1)/2
We use Carl Friedrich Gauss method
2. If a,b,c...n are consecutive integers starting from any number then the answer is:
const sum = (a, b) => (b*(b+1)-(a-1)*a)/2
We use Carl Friedrich Gauss method
3. If a,b,c...n are non-consecutive any integers then the answer is:
const sum = a => b => b ? sum(a+b) : a
We use recursive here.
Watch the solutions in action here: https://repl.it/@VinitKhandelwal/sum-of-n-numbers
Watch the solutions in action here: https://repl.it/@VinitKhandelwal/sum-of-n-numbers
Comments
Post a Comment