Created
April 21, 2018 14:00
-
-
Save colevandersWands/fba599e19bda4ac1f30b2b3cbb4cf52f to your computer and use it in GitHub Desktop.
on nested loops
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
as usual, run these in pythontutor |
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
// each time num grows by 1, three more loopings are executed | |
function multiplication(num) { | |
let returner = 0; | |
for (let k = 0; k < num; k++) { | |
returner = returner + num; | |
} | |
for (let j = 0; j < num; j++) { | |
returner = returner + num; | |
} | |
for (let i = 0; i < num; i++) { | |
returner = returner + num; | |
} | |
return returner; | |
} | |
addition(2) | |
addition(3) | |
// each time num grows by 1, number of loopings grows much faster | |
function exponent(num) { | |
let returner = 0; | |
for (let k = 0; k < num; k++) { | |
for (let j = 0; j < num; j++) { | |
for (let i = 0; i < num; i++) { | |
returner = returner + num; | |
} | |
} | |
} | |
return returner; | |
} | |
exponent(2) | |
exponent(3) |
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 shallow(num) { | |
let returner = 0; | |
for (let i = 0; i < num; i++) { | |
returner = returner + num; | |
} | |
return returner; | |
} | |
function nested(num) { | |
let returner = 0; | |
for (let j = 0; j < num; j++) { | |
for (let i = 0; i < num; i++) { | |
returner = returner + num; | |
} | |
} | |
return returner; | |
} | |
function deeplyNested(num) { // exponential (^ input) | |
let returner = 0; | |
for (let k = 0; k < num; k++) { | |
for (let j = 0; j < num; j++) { | |
for (let i = 0; i < num; i++) { | |
returner = returner + num; | |
} | |
} | |
} | |
return returner; | |
} | |
function overlyNested(num) { | |
let returner = 0; | |
for (let l = 0; l < num; l++) { | |
for (let k = 0; k < num; k++) { | |
for (let j = 0; j < num; j++) { | |
for (let i = 0; i < num; i++) { | |
returner = returner + num; | |
} | |
} | |
} | |
} | |
return returner; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment