forums
new posts
donate
UER Store
events
location db
db map
search
members
faq
terms of service
privacy policy
register
login




UER Forum > Private Boards Index > Tech Talk > Help in programming question (Viewed 968 times)
Macsbug 

Noble Donor


Location: St. Paul, MN
Gender: Male
Total Likes: 1 like


Safety First!

 |  |  | AIM Message
Help in programming question
< on 10/4/2004 9:07 PM >
Reply with Quote
Posted on Forum: UER Forum
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.




"Believe those who are seeking the truth; doubt those who find it."
Macsbug 

Noble Donor


Location: St. Paul, MN
Gender: Male
Total Likes: 1 like


Safety First!

 |  |  | AIM Message
Re: Help in programming question
< Reply # 1 on 10/5/2004 12:49 AM >
Reply with Quote
Posted on Forum: UER Forum
Fuck that shit, I figured it out. After many hours of stupidity...

(define (exp b n)
(expt-iter b n b 1))

(define (expt-iter b n sofar count)
(cond ((= count n) sofar)
((= n 0) 1)
((< count 2) (expt-iter b n (* sofar b) (+ count 1)))
((<= (+ count count) n) (expt-iter b n (* sofar sofar) (+ count count)))
(else (expt-iter b n (* sofar b) (+ count 1)))))




"Believe those who are seeking the truth; doubt those who find it."
UER Forum > Private Boards Index > Tech Talk > Help in programming question (Viewed 968 times)


Add a poll to this thread



This thread is in a public category, and can't be made private.



All content and images copyright © 2002-2024 UER.CA and respective creators. Graphical Design by Crossfire.
To contact webmaster, or click to email with problems or other questions about this site: UER CONTACT
View Terms of Service | View Privacy Policy | Server colocation provided by Beanfield
This page was generated for you in 78 milliseconds. Since June 23, 2002, a total of 740319877 pages have been generated.