-
3 Comments
Micah Beckman
on 5 Sep 2016
Okay, so we can definitely do better than a for loop...
Zhengyi
on 21 Mar 2018
@Micah Beckman no, this solution is not an "efficient" answer even though it scores high... one should use sum(1:n) to replace a for loop sum.
Aravind C G
on 7 Aug 2021
While people are tricking the scoring mechanism using regexp, sum(1:n) isn't the most efficient.
It's helpful to recognize that this is an arithmetic series starting at 1 and ending at n with an increments of 1. The sum of such an arithmetic series is n*(n+1)/2. You can see the difference if you use 'tic' 'toc' to time sum(1:n) and n*(n+1)/2 for very large n.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!