Last active
July 30, 2023 18:34
-
-
Save ahsanhabibleon/b83ba335a949172bfc66fa7fe4c819f5 to your computer and use it in GitHub Desktop.
Ostad_cracking_coding_interview_assignment_1
This file contains hidden or 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
| // using `formula` (time complexity O(1), space complexity O(1)) | |
| function sum_of_natural_numbers(n) { | |
| return (n * (n + 1)) / 2; | |
| } | |
| // using `for` loop (time complexity O(n), space complexity O(1)) | |
| function sum_of_natural_numbers_using_for_loop(n) { | |
| let SUM = 0; | |
| for (let i = 0; i <= n; i++) { | |
| SUM += i; | |
| } | |
| return SUM; | |
| } | |
| // using `while` loop (time complexity O(n), space complexity O(1)) | |
| function sum_of_natural_numbers_using_while_loop(n) { | |
| let SUM = 0; | |
| let i = 0; | |
| while (i <= n) { | |
| SUM += i; | |
| i++; | |
| } | |
| return SUM; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment