Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save moriarty99779/83880be8d00f6904318cf47deb02cab5 to your computer and use it in GitHub Desktop.
Save moriarty99779/83880be8d00f6904318cf47deb02cab5 to your computer and use it in GitHub Desktop.
PHP Find sum of all numbers from 1..N
function get_sum(int $n = 100) {
$sum = $n * ($n + 1) / 2;
return $sum;
}
@moriarty99779
Copy link
Author

This is the basic algorithm that is often used to answer questions found on entry-level programming job interview questions. Basically, take the highest number $n, add one to it - $n + 1, multiply it by the original $n, then divide by 2.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment