I'm in an intro to programming class, we are programming in scheme. One of our lab questions is to create an interative algorythom to exponentiate numbers using succsessive squaring, I think... So instead of writing a procedure to multiply x by x n times to solve x^n, I'm supposed to write one that recognizes that x^2n=x^n*x^n, which would therefore take less steps to complete. I wrote the procedure so it checks if the number is divisable by 2, and if so, it divides n by 2, and adds one to shouldsquare, which is later used to square the result I get. If not, it multiplies the product so far by x, and subtracts 1 from n, when n=0, all the squaring takes place, and once that's done, a result is printed. But it don't work. Here are some sample cases: STk> (exp 2 2) 8 STk> (exp 2 3) 16 STk> (exp 2 4) 32 STk> (exp 2 5) 64 STk> (exp 2 6) 64 STk> (exp 2 7) 128 STk> (exp 2 8) 512 STk> (exp 2 9) 1024 STk> (exp 2 10) 1024 STk> (exp 2 11) 2048 STk> (exp 2 12) 1024 - 2^6,10,12 fail. Same with 3^6,10,12 And ideas? I can post my code too if that would help. I think I just missed something simple, and I don't know why, but ^12 comes back the same as ^9, instead as same as ^11 which I think is weird.
|