I want to take Input from the user as Big-Integer and manipulate it into a For loop
BigInteger i; for(BigInteger i=0; i<=100000; i++) { System.out.println(i); }
But it won't work
can any body help me.
BigInteger class provides operations analogues to all of Java's primitive integer operators and for all relevant methods from java. lang. Math. It also provides operations for modular arithmetic, GCD calculation, primality testing, prime generation, bit manipulation, and a few other miscellaneous operations.
The java. math. BigInteger. add(BigInteger val) returns a BigInteger object whose value is (this + val).
You use these syntax instead:
BigInteger i = BigInteger.valueOf(100000L); // long i = 100000L; i.compareTo(BigInteger.ONE) > 0 // i > 1 i = i.subtract(BigInteger.ONE) // i = i - 1
So here's an example of putting it together:
for (BigInteger bi = BigInteger.valueOf(5); bi.compareTo(BigInteger.ZERO) > 0; bi = bi.subtract(BigInteger.ONE)) { System.out.println(bi); } // prints "5", "4", "3", "2", "1"
Note that using BigInteger
as a loop index is highly atypical. long
is usually enough for this purpose.
java.math.BigInteger
int compareTo(BigInteger val)
from interface Comparable<T>
BigInteger subtract(BigInteger val)
BigInteger add(BigInteger val)
static BigInteger valueOf(long val)
compareTo
idiomFrom the documentation:
This method is provided in preference to individual methods for each of the six boolean comparison operators (
<
,==
,>
,>=
,!=
,<=
). The suggested idiom for performing these comparisons is: (x.compareTo(y)
<op>
0
), where<op>
is one of the six comparison operators.
In other words, given BigInteger x, y
, these are the comparison idioms:
x.compareTo(y) < 0 // x < y x.compareTo(y) <= 0 // x <= y x.compareTo(y) != 0 // x != y x.compareTo(y) == 0 // x == y x.compareTo(y) > 0 // x > y x.compareTo(y) >= 0 // x >= y
This is not specific to BigInteger
; this is applicable to any Comparable<T>
in general.
BigInteger
, like String
, is an immutable object. Beginners tend to make the following mistake:
String s = " hello "; s.trim(); // doesn't "work"!!! BigInteger bi = BigInteger.valueOf(5); bi.add(BigInteger.ONE); // doesn't "work"!!!
Since they're immutable, these methods don't mutate the objects they're invoked on, but instead return new objects, the results of those operations. Thus, the correct usage is something like:
s = s.trim(); bi = bi.add(BigInteger.ONE);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With