Integer Power

View: New views
2 Messages — Rating Filter:   Alert me  

Integer Power

by Paulo J. Matos :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Hello all,

Is there a way to compute a^b where both a and b are integers?
I can't find this on util/integer.als, nor can I figure out how to
"implement" this in Alloy given that afaik there's not really the
concept of looping on it.

Cheers,

--
Paulo Jorge Matos - pocm at soton.ac.uk
http://www.personal.soton.ac.uk/pocm
PhD Student @ ECS
University of Southampton, UK
Sponsor ECS runners - Action against Hunger:
http://www.justgiving.com/ecsrunslikethewind

Re: Integer Power

by Felix Chang-2 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

On Fri, 14 Mar 2008, Paulo J. Matos wrote:
> Is there a way to compute a^b where both a and b are integers?
> I can't find this on util/integer.als, nor can I figure out how to
> "implement" this in Alloy given that afaik there's not really the
> concept of looping on it.

Given the fact that the integer range is so limited,
you might as well hard code the result:

fun pow[a, b: Int]: Int {
        a=0 => 0
   else a=1 => 1
   else b=0 => 1
   else b=1 => a
   else b=2 => a.mul[a]
   else b=3 => a.mul[a].mul[a]
   else b=4 => a.mul[a].mul[a].mul[a]
   else b=5 => a.mul[a].mul[a].mul[a].mul[a]
   else b=6 => a.mul[a].mul[a].mul[a].mul[a].mul[a]
   else b=7 => a.mul[a].mul[a].mul[a].mul[a].mul[a].mul[a]
   else -1
}

We know 2^8=256
Bitwidth of 8 gives you -128..127
Bitwidth of 9 gives you -256..255
Bitwidth of 10 gives you -512..511

So unless your integer bitwidth is 10 or above,
then the function above will always compute the correct solution
when a>=0 and b>=0 and a^b is in range.

Sincerely,
Felix Chang
Alloy4 Developer



LightInTheBox - Buy quality products at wholesale price