问题
I am trying to implement a repeated squaring algorithm in SML. I want it to be tail recursive.
The goal is to multiply all x^k where k is 2^m and 2^m is a 1 in the binary representation of n.
E.g, for x^25, calculate x^1 * x^8 * x^16 because 16 + 8 + 1 = 25
I have no idea how to represent a number by it's binary parts, or to use bitwise operations to check manually (because from what I can tell SML has no bitwise operations).
I would prefer to use the out-of-the-box SML library, so no importing other libraries.
This is a homework problem, so if you can answer without completely giving it away that would be great.
Edit: I'm using SML of New Jersey.
回答1:
Thanks to matt, I found the solution.
Using the Word type from the SML basis library, I used:
Word.andb(Word.fromInt(x), Word.fromInt(y)) > Word.fromInt(0)
来源:https://stackoverflow.com/questions/35740771/how-do-i-inspect-an-integers-base-2-representation-in-standard-ml