Ask your own question, for FREE!
MIT 6.00 Intro Computer Science (OCW) 18 Online
OpenStudy (anonymous):

Lecture 8 handout question: def exp3(a,b): if b == 1: return a if (b%2)*2 == b: return exp3(a*a, b/2) else: return a*exp3(a,b-1) line 4 tests whether or not b is even. b%2 is used which will return either a 0 or a 1. Shouldn't it be b/2 instead?

OpenStudy (vaboro):

If b is not integer b%2 will not be 0 if b is even; whereas (b%2)*2 will be b

OpenStudy (anonymous):

Both ways should work correctly. They actually do the same thing (test b to see if it's even).

OpenStudy (anonymous):

Sorry-but I still don't see it... if b is 6 (even), then 6%2 is 0, right? 0 * 2 is 0, making 0==b false. So an even number will skip this loop and the else loop (for odd numbers) will run. The if loop never runs. I'm missing something obvious, aren't I?

OpenStudy (vaboro):

Right, if it were division instead of modulus, (b/2)*b then it would make perfect sense. Anyway, I should probably need to refresh the lecture in order to be able to tell for sure what it means.

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!