Re: how to use recursive algorithm to determine all of the arrangements?



Oliver Wong wrote:
<opalpa@xxxxxxxxx> wrote in message news:1147153506.499376.122360@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


btw, How do I check for overflow on multiplication in Java (or any
other arithmetic operation)?


The simplest way is to check for integer overflow is to do the multiplication in floating point precision, and check if the result is larger than what would fit in whatever primitive type you're trying to store the value in.

e.g.

<pseudocode>
int a, b, result;
double temp = (double)a * (double)b;
if (temp > max_int_value) {
handleOverFlow();
} else {
result = (int)temp;
}
</pseudocode>

In the case of int, you could use long instead of double.

- Oliver

Note that this should only be used, as written, for int and smaller
types, not long. It depends on all int values being exactly
representable as doubles, so that if there is no overflow temp does
contain the exact answer.

This program:

public class TestMult {
public static void main(String[] args) {
long a = 0x0fffffffffffffffL;
long b = 3;
long result=0;
double temp = (double)a * (double)b;
if (temp > Long.MAX_VALUE) {
handleOverFlow();
System.exit(3);
} else {
result = (long)temp;
}
System.out.println("result="+result+" correct answer="+a*b);
}
private static void handleOverFlow() {
System.out.println("Overflow detected");
}
}

prints:

result=3458764513820540928 correct answer=3458764513820540925

For long, using BigInteger instead of double would be slower but more
reliable.

Patricia
.



Relevant Pages