Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save ahsanhabibleon/b83ba335a949172bfc66fa7fe4c819f5 to your computer and use it in GitHub Desktop.

Select an option

Save ahsanhabibleon/b83ba335a949172bfc66fa7fe4c819f5 to your computer and use it in GitHub Desktop.
Ostad_cracking_coding_interview_assignment_1
// 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