Reputation: 11
If I need to calculate a variable "totalIPaddress" whose value is 2^($blocksize) what will be the xquery statement for this?
<IPaddress>
<startIPaddress>192.168.1.1</startIPaddress>
<blocksize>4</blocksize>
</IPaddress>
Upvotes: 1
Views: 1319
Reputation: 1
There is a math:pow
function:
math:pow(
$x as xs:double?,
$y as xs:numeric
) as xs:double?
Upvotes: 0
Reputation: 243529
Here is a particularly efficient way of calculating powers -- with logarithmic time complexity (O(log(N)):
declare function local:pow($x as xs:double , $n as xs:integer ) as xs:double
{
if($n eq 0)
then 1
else
(let $h := $n idiv 2,
$halfResult := local:pow($x, $h)
return
if($n mod 2 eq 0)
then $halfResult * $halfResult
else $x * $halfResult * $halfResult
)
};
local:pow(2,10)
producing the expected correct result:
1024
Upvotes: 2
Reputation: 163458
Recursion is your friend:
declare function f:two-to-the($n as xs:integer) as xs:integer {
if ($n = 0) then 1 else 2 * f:two-to-the($n - 1)
};
Upvotes: 1
Reputation: 16917
Except for math:pow, the simplest way would be to just hardcode it:
(1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, 67108864, 134217728, 268435456, 536870912, 1073741824, 2147483648, 4294967296)[$blocksize + 1]
works also in XPath 2.
Upvotes: 0