Hey!
Odd * Odd numbers are always odd correct??
Can you check the following numbers?
7^19,
9^17,
9^18,
9^19 ? I have a program that says they are all divisible by 2.
Isnt that peculiar?
andrec
public class logic {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
double eSquare=0;
int evenPlus1=0;
for (int even = 0; even < 10; even+=2) {
for (int n=0;n < 20; n+=1) {
evenPlus1 =even+1;
eSquare = Math.pow(evenPlus1,n); //(even+1)^n
if ((eSquare % 2) ==0)
System.out.println(evenPlus1+"^"+n+" "+eSquare+" is divisible by 2");
}
}
}
}
its java.
later,
andrec
This effect is probably due to overflow. Double numbers are represented as where m is the mantissa and e is the exponent. Positive integers can only be represented precisely if they fit in the mantissa. According to this document, type double allots 53 bits to the mantissa. Interestingly, , so requires 54 bits to be represented precisely. Therefore, as a double, it will be represented as for some m, which is an even number.
This must be because both C and Java implement the IEEE 754 standard for binary floating point numbers. This tutorial says, "This data type [float] should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead." Also, Java long type has 64 bits, so it can precisely represent positive integers up to 2^63 - 1, which is more than double can.
That is the whole of this opinion piece.
It may be fifteen years old, but it is still true today.
Hi Andrec,
If you are going to use Java for big integers, use BigInteger, not BigDecimal. Here's code for computing 7^19 mod 2:
BigInteger seven = BigInteger.valueOf(7);
BigInteger nineteen = BigInteger.valueOf(19);
BigInteger two = BigInteger.valueOf(2);
BigInteger odd = seven.modPow(nineteen, two);
System.out.println(odd.toString());
As expected, output is 1.
A more interesting example is computing the last three digits of 151^192:
BigInteger onefiftyone = BigInteger.valueOf(151);
BigInteger oneninetytwo = BigInteger.valueOf(192);
BigInteger thousand = BigInteger.valueOf(1000);
BigInteger digits = onefiftyone.modPow(oneninetytwo, thousand);
System.out.println(digits.toString());
Output is 801
You can do this example by hand, but I wouldn't want to.