Suppose I want to calculate 2^10000 using Math.pow(). For which my code is-
long num = (long)Math.pow(2, 10000);
System.out.println(num);
Here I'm getting output as 9223372036854775807 which I guess is the limit of long. But if I write like this-
double n = Math.pow(2, 10000);
System.out.println(n);
the o/p is Infinity which is a bit weird. Anyone please help me with this.
This will work, but be aware that BigInteger is not very efficient and I don't consider it suitable for production work for math problems.
public static void main( String[] args ) {
BigInteger two = new BigInteger( "2" );
BigInteger twoToTenThousand = two.pow( 10000 );
System.out.println( twoToTenThousand );
}
2^10000 overflows the limit of both longs and doubles. However, in Java, overflowing in longs and doubles are treated differently. If you add 1 to the largest possible value in a long, you wrap around and the result is the smallest possible value for a long, equal to -2^63. On the other hand, if you add 1 to the largest possible value in a double, you get Double.POSITIVE_INFINITY. See https://docs.oracle.com/javase/8/docs/api/java/lang/Long.html and https://docs.oracle.com/javase/8/docs/api/java/lang/Double.html for more information.
Related
I am trying to find the value of 1/(2^n) where 0 <=n<= 200
I have tried to use biginteger but it is giving output as zero . I want exact number after division .
import java.math.BigInteger;
public class Problem2 {
public static void main(String args[]){
BigInteger bi1 = new BigInteger("2").pow(200);
BigInteger bi2 = BigInteger.ONE;
BigInteger bi3 = bi2.divide(bi1);
System.out.println(bi3); //why it giving output zero
}
}
On use of BigDecimal it is giving exponential value , but how to get exact value without exponent.
because 0< bi3 <1, so an integer result is 0. Try BigDecimal in place of BigInteger
BigInteger works like Integer in that the result of calculations between two integers is an integer.
If we write int n = 1 / 1024 the result is likewise 0.
Try this:
BigDecimal b = new BigDecimal( new BigInteger("2").pow(200) );
BigDecimal one = new BigDecimal(1);
BigDecimal quotient = one.divide(b);
System.out.println(quotient); //scientific notation. (140 significant digits)
System.out.println(quotient.toPlainString()); //regular notation with leading zeros
The result of 1/(2^200) is going to be extremely small, and definitely not an integer, so the zero result you are getting is "correct".
The answer is so small that even Java double (64 bit) will run out of precision. You may be able to coax BigDecimal to give the correct answer, but the performance will almost certainly be terrible.
Why do you need such precision? The number of atoms in the universe has been estimated at around 10^38, which I think is around 2^150. We can help better if we know what you are trying to do.
Try for float/Double in case you get result in decimal points.
I am trying to printout fibonacci series upto 'N' numbers. All works as per expectation till f(92) but when I am trying to get the value of f(93), values turns out in negative: "-6246583658587674878". How this could be possible? What is the mistake in the logic below?
public long fibo(int x){
long[] arr = new long[x+1];
arr[0]=0;
arr[1]=1;
for (int i=2; i<=x; i++){
arr[i]=arr[i-2]+arr[i-1];
}
return arr[x];
}
f(91) = 4660046610375530309
f(92) = 7540113804746346429
f(93) = -6246583658587674878
Is this because of data type? What else data type I should use for printing fibonacci series upto N numbers? N could be any integer within range [0..10,000,000].
You've encountered an integer overflow:
4660046610375530309 <-- term 91
+7540113804746346429 <-- term 92
====================
12200160415121876738 <-- term 93: the sum of the previous two terms
9223372036854775808 <-- maximum value a long can store
To avoid this, use BigInteger, which can deal with an arbitrary number of digits.
Here's your implementation converted to use BigDecimal:
public String fibo(int x){
BigInteger[] arr = new BigInteger[x+1];
arr[0]=BigInteger.ZERO;
arr[1]=BigInteger.ONE;
for (int i=2; i<=x; i++){
arr[i]=arr[i-2].add(arr[i-1]);
}
return arr[x].toString();u
}
Note that the return type must be String (or BigInteger) because even the modest value of 93 for x produces a result that is too great for any java primitive to represent.
This happened because the long type overflowed. In other words: the number calculated is too big to be represented as a long, and because of the two's complement representation used for integer types, after an overflow occurs the value becomes negative. To have a better idea of what's happening, look at this code:
System.out.println(Long.MAX_VALUE);
=> 9223372036854775807 // maximum long value
System.out.println(Long.MAX_VALUE + 1);
=> -9223372036854775808 // oops, the value overflowed!
The value of fibo(93) is 12200160415121876738, which clearly is greater than the maximum value that fits in a long.
This is the way integers work in a computer program, after all they're limited and can not be infinite. A possible solution would be to use BigInteger to implement the method (instead of long), it's a class for representing arbitrary-precision integers in Java.
As correctly said in above answers, you've experienced overflow, however with below java 8 code snippet you can print series.
Stream.iterate(new BigInteger[] {BigInteger.ZERO, BigInteger.ONE}, t -> new BigInteger[] {t[1], t[0].add(t[1])})
.limit(100)
.map(t -> t[0])
.forEach(System.out::println);
How can I examine each digit (System.out.println() each digit, for instance) of a BigInteger in Java? Is there any other way other than converting it to a string?
Straight-forward code prints digits from the last towards the first:
private static void printDigits(BigInteger num) {
BigInteger[] resultAndRemainder;
do {
resultAndRemainder = num.divideAndRemainder(BigInteger.TEN);
System.out.println(Math.abs(resultAndRemainder[1].intValue()));
num = resultAndRemainder[0];
} while (num.compareTo(BigInteger.ZERO) != 0);
}
The BigInteger API docs do not appear to provide any functionality as such. Moreover, the numbers are quite likely not represented in base 10 (since it would be quite inefficient). So it is most likely that the only way to inspect the decimal digits of a BigInteger is to look at its string representation.
You could of course use basic math to calculate each digit. Especially the method divideAndRemainder might help here. But I doubt, that this is more efficient than converting to a String and examing the characters. BigInteger math is more expensive than plain int or long math after all.
I think the only way you could do it is converting it into a String and verify each char. Here is an example:
BigInteger bigInteger = new BigInteger("123");
String bigIntegerValue = bigInteger.toString();
for(int i = 0; i < bigIntegerValue.length(); i++) {
System.out.println(bigIntegerValue.charAt(i));
}
Maybe you can try to examine each bit in your biginteger using BitSet like this,
BitSet bitSet = BitSet.valueOf(bigInteger.toByteArray());
It seems pretty simple what you need to do get each digit of a number.
create a loop that tracks if you number is greater then ten and then preform a mod 10 operation on it and then divide by ten.
while (num >10)
{
System.out.println(num%10);
num = num/10;
}
I'm playing with numbers in Java, and want to see how big a number I can make. It is my understanding that BigInteger can hold a number of infinite size, so long as my computer has enough Memory to hold such a number, correct?
My problem is that BigInteger.pow accepts only an int, not another BigInteger, which means I can only use a number up to 2,147,483,647 as the exponent. Is it possible to use the BigInteger class as such?
BigInteger.pow(BigInteger)
Thanks.
You can write your own, using repeated squaring:
BigInteger pow(BigInteger base, BigInteger exponent) {
BigInteger result = BigInteger.ONE;
while (exponent.signum() > 0) {
if (exponent.testBit(0)) result = result.multiply(base);
base = base.multiply(base);
exponent = exponent.shiftRight(1);
}
return result;
}
might not work for negative bases or exponents.
You can only do this in Java by modular arithmetic, meaning you can do a a^b mod c, where a,b,c are BigInteger numbers.
This is done using:
BigInteger modPow(BigInteger exponent, BigInteger m)
Read the BigInteger.modPow documentation here.
The underlying implementation of BigInteger is limited to (2^31-1) * 32-bit values. which is almost 2^36 bits. You will need 8 GB of memory to store it and many times this to perform any operation on it like toString().
BTW: You will never be able to read such a number. If you tried to print it out it would take a life time to read it.
Please be sure to read the previous answers and comments and understand why this should not be attempted on a production level application. The following is a working solution that can be used for testing purposes only:
Exponent greater than or equal to 0
BigInteger pow(BigInteger base, BigInteger exponent) {
BigInteger result = BigInteger.ONE;
for (BigInteger i = BigInteger.ZERO; i.compareTo(exponent) != 0; i = i.add(BigInteger.ONE)) {
result = result.multiply(base);
}
return result;
}
This will work for both positive and negative bases. You might want to handle 0 to the power of 0 according to your needs, since that's technically undefined.
Exponent can be both positive or negative
BigDecimal allIntegersPow(BigInteger base, BigInteger exponent) {
if (BigInteger.ZERO.compareTo(exponent) > 0) {
return BigDecimal.ONE.divide(new BigDecimal(pow(base, exponent.negate())), 2, RoundingMode.HALF_UP);
}
return new BigDecimal(pow(base, exponent));
}
This re-uses the first method to return a BigDecimal with 2 decimal places, you can define the scale and rounding mode as per your needs.
Again, you should not do this in a real-life, production-level system.
java wont let you do BigInteger.Pow(BigInteger) but you can just put it to the max integer in a loop and see where a ArithmeticException is thrown or some other error due to running out of memory.
2^2,147,483,647 has at least 500000000 digit, in fact computing pow is NPC problem, [Pow is NPC in the length of input, 2 input (m,n) which they can be coded in O(logm + logn) and can take upto nlog(m) (at last the answer takes n log(m) space) which is not polynomial relation between input and computation size], there are some simple problems which are not easy in fact for example sqrt(2) is some kind of them, you can't specify true precision (all precisions), i.e BigDecimal says can compute all precisions but it can't (in fact) because no one solved this up to now.
I can suggest you make use of
BigInteger modPow(BigInteger exponent, BigInteger m)
Suppose you have BigInteger X, and BigInteger Y and you want to calculate BigInteger Z = X^Y.
Get a large Prime P >>>> X^Y and do Z = X.modPow(Y,P);
For anyone who stumbles upon this from the Groovy side of things, it is totally possible to pass a BigInteger to BigInteger.pow().
groovy> def a = 3G.pow(10G)
groovy> println a
groovy> println a.class
59049
class java.math.BigInteger
http://docs.groovy-lang.org/2.4.3/html/groovy-jdk/java/math/BigInteger.html#power%28java.math.BigInteger%29
Just use .intValue()
If your BigInteger is named BigValue2, then it would be BigValue2.intValue()
So to answer your question, it's
BigValue1.pow(BigValue2.intValue())
I have an array of ints ie. [1,2,3,4,5] . Each row corresponds to decimal value, so 5 is 1's, 4 is 10's, 3 is 100's which gives value of 12345 that I calculate and store as long.
This is the function :
public long valueOf(int[]x) {
int multiplier = 1;
value = 0;
for (int i=x.length-1; i >=0; i--) {
value += x[i]*multiplier;
multiplier *= 10;
}
return value;
}
Now I would like to check if value of other int[] does not exceed long before I will calculate its value with valueOf(). How to check it ?
Should I use table.length or maybe convert it to String and send to
public Long(String s) ?
Or maybe just add exception to throw in the valueOf() function ?
I hope you know that this is a horrible way to store large integers: just use BigInteger.
But if you really want to check for exceeding some value, just make sure the length of the array is less than or equal to 19. Then you could compare each cell individually with the value in Long.MAX_VALUE. Or you could just use BigInteger.
Short answer: All longs fit in 18 digits. So if you know that there are no leading zeros, then just check x.length<=18. If you might have leading zeros, you'll have to loop through the array to count how many and adjust accordingly.
A flaw to this is that some 19-digit numbers are valid longs, namely those less than, I believe it comes to, 9223372036854775807. So if you wanted to be truly precise, you'd have to say length>19 is bad, length<19 is good, length==19 you'd have to check digit-by-digit. Depending on what you're up to, rejecting a subset of numbers that would really work might be acceptable.
As others have implied, the bigger question is: Why are you doing this? If this is some sort of data conversion where you're getting numbers as a string of digits from some external source and need to convert this to a long, cool. If you're trying to create a class to handle numbers bigger than will fit in a long, what you're doing is both inefficient and unnecessary. Inefficient because you could pack much more than one decimal digit into an int, and doing so would give all sorts of storage and performance improvements. Unnecessary because BigInteger already does this. Why not just use BigInteger?
Of course if it's a homework problem, that's a different story.
Are you guaranteed that every value of x will be nonnegative?
If so, you could do this:
public long valueOf(int[]x) {
int multiplier = 1;
long value = 0; // Note that you need the type here, which you did not have
for (int i=x.length-1; i >=0; i--) {
next_val = x[i]*multiplier;
if (Long.MAX_LONG - next_val < value) {
// Error-handling code here, however you
// want to handle this case.
} else {
value += next_val
}
multiplier *= 10;
}
return value;
}
Of course, BigInteger would make this much simpler. But I don't know what your problem specs are.