Created
May 6, 2024 14:48
-
-
Save moriarty99779/83880be8d00f6904318cf47deb02cab5 to your computer and use it in GitHub Desktop.
PHP Find sum of all numbers from 1..N
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
function get_sum(int $n = 100) { | |
$sum = $n * ($n + 1) / 2; | |
return $sum; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.