Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
How do you use BigInteger exactly? I'm trying to do the following:
import java.util.*;
import java.math.*;
public class hello{
public static void main(String[] args){
for(int i = 0; i <= 1024; i++){
BigInteger a = new BigInteger(Math.pow(2,i));
System.out.println(a);
}
}
}
I want a to hold this potentially huge value so that I can manipulate it in the program.
Math.pow returns a double and 2^i cannot be represented in a double as it is way too big.
You need to use the pow method from BigInteger:
BigInteger a = BigInteger.valueOf(2).pow(i);
Java's Math class does not have methods of BigInteger.
Use BigInteger's method instead.
BigInteger a = new BigInteger(Math.pow(2,i));
System.out.println(a);
should be
BigInteger a = new BigInteger("2").pow(i); // String to BigInteger, and then power
System.out.println(a);
or
BigInteger a = BigInteger.valueOf(2).pow(i); // long to BigInteger, and then power
System.out.println(a);
There is no BigInteger(double) constructor. Try using new BigInteger(String) and instead of Math.pow use BigInteger#pow method which also returns BigInteger.
for (int i = 0; i < 200; i++) {
BigInteger a = new BigInteger("2").pow(i);
System.out.println(a);
}
Think of BigInteger like a string. You can't use any of the arithmetic, relational, and unary operators on it like you would do for primitive data types. Instead, you have to use the methods inside the BigInteger class to perform operations on BigInteger.
For example, if you wanted to multiply two BigIntegers, you can't do this:
BigInteger a = (new BigInteger("5"))*(new BigInteger("7"));
Instead, you must declare two BigIntegers and then multiply them with .multiply()
BigInteger a = new BigInteger("5");//note how these numbers are like strings
BigInteger b = new BigInteger("7");
BigInteger c = a.multiply(b);
So in regards to your program where you want to print the powers of two, you have to use BigInteger in a slightly different way.
for(int i = 0; i <= 1024; i++){
BigInteger a = new BigInteger("2").pow(i);
System.out.println(a);
}
Note how the value inside the .pow() is an int. That's specified in the BigInteger documentation. Essentially, BigInteger is a very powerful tool when calculating large values, but it is also more tedious and requires lengthier and more involved code.
Related
I need to find 2 to-the-power N where N is a very large number (Java BigInteger type)
Java BigInteger Class has pow method but it takes only integer value as exponent.
So, I wrote a method as follows:
static BigInteger twoToThePower(BigInteger n)
{
BigInteger result = BigInteger.valueOf(1L);
while (n.compareTo(BigInteger.valueOf((long) Integer.MAX_VALUE)) > 0)
{
result = result.shiftLeft(Integer.MAX_VALUE);
n = n.subtract(BigInteger.valueOf((long) Integer.MAX_VALUE));
}
long k = n.longValue();
result = result.shiftLeft((int) k);
return result;
}
My code works fine, I am just sharing my idea and curious to know if there is any other better idea?
Thank you.
You cannot use BigInteger to store the result of your computation. From the javadoc :
BigInteger must support values in the range -2^Integer.MAX_VALUE (exclusive) to +2^Integer.MAX_VALUE (exclusive) and may support values outside of that range.
This is the reason why the pow method takes an int. On my machine, BigInteger.ONE.shiftLeft(Integer.MAX_VALUE) throws a java.lang.ArithmeticException (message is "BigInteger would overflow supported range").
Emmanuel Lonca's answer is correct. But, by Manoj Banik's idea, I would like to share my idea too.
My code do the same thing as Manoj Banik's code in faster way. The idea is init the buffer, and put the bit 1 in to correct location. I using the shift left operator on 1 byte instead of shiftLeft method.
Here is my code:
static BigInteger twoToThePower(BigInteger n){
BigInteger eight = BigInteger.valueOf(8);
BigInteger[] devideResult = n.divideAndRemainder(eight);
BigInteger bufferSize = devideResult[0].add(BigInteger.ONE);
int offset = devideResult[1].intValue();
byte[] buffer = new byte[bufferSize.intValueExact()];
buffer[0] = (byte)(1 << offset);
return new BigInteger(1,buffer);
}
But it still slower than BigInteger.pow
Then, I found that class BigInteger has a method called setBit. It also accepts parameter type int like the pow method. Using this method is faster than BigInteger.pow.
The code can be:
static BigInteger twoToThePower(BigInteger n){
return BigInteger.ZERO.setBit(n.intValueExact());
}
Class BigInteger has a method called modPow also. But It need one more parameter. This means you should specify the modulus and your result should be smaller than this modulus. I did not do a performance test for modPow, but I think it should slower than the pow method.
By using repeated squaring you can achieve your goal. I've posted below sample code to understand the logic of repeated squaring.
static 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;
}
An interesting question. Just to add a little more information to the fine accepted answer, examining the openjdk 8 source code for BigInteger reveals that the bits are stored in an array final int[] mag;. Since arrays can contain at most Integer.MAX_VALUE elements this immediately puts a theoretical bound on this particular implementation of BigInteger of 2(32 * Integer.MAX_VALUE). So even your method of repeated left-shifting can only exceed the size of an int by at most a factor of 32.
So, are you ready to produce your own implementation of BigInteger?
So I was given a problem telling me to make a table of factorials of integers up to number 30. The book specifically tells me to use the object BigInteger. (using BigInteger big= BigInteger.valueOf(x)) However doing so is pretty tricky and gives me a bunch of errors that I have no idea how to fix.
for example
public static BigInteger factorial(int a){
if(a == 0){
return BigInteger.valueOf(1);
}
else{
return BigInteger.valueOf(a*BigInteger.valueOf(factorial(a-1)));// this will keep giving me an error message that I need to change the value type to "long" and back and forth to BIgInteger. I've tried many different variations including where I use BigInteger.valueOf(..) to every values.
}
}
Do you know a correct way to use the BigInteger object?
When would you ever use BigInteger instead of double?
import java.math.BigInteger;
public class BigInt {
public static double factorial(int a){
if(a == 0){
return 1;
}
else{
return a* factorial(a-1);
}
}
public static void table(int a){
for(int i =0; i<=a; i++){
System.out.println(i + ", " + factorial(i) );
}
}
public static void main(String[] args) {
table(30);
}
}
When you are using BigInteger you can't use operators such as *. You must use methods of the BigInteger class :
return factorial(a-1).multiply(a);
The reason for using BigInteger instead of double is precision. double has limited precision, so large integers can't be represented accurately.
EDIT: You should actually use
return BigInteger.valueOf(a).multiply(factorial(a-1));
since BigInteger multiply(long v) is package private.
Instead of
BigInteger.valueOf(a*BigInteger.valueOf(factorial(a-1)))
try
factorial(a - 1).multiply(BigInteger.valueOf(a))
You are currently trying to use the * operator to multiply an int and BigInteger; that isn't allowed in Java, since operator overloading isn't supported.
As to why you'd use BigInteger instead of double: double only supports a finite number of significant figures before it starts rounding. Using BigInteger allows you to have arbitrarily-large numbers.
It's not a primitive type so * doesn't work.
For detail description read this article, A brief description about use of object BigInteger. I Hope it will help you a lot.
Java:Why should we use BigDecimal instead of Double in the real world?
When we deal with numbers related to money , where we require results in nearest precision . Then we use BigInteger instead of double. But comparing with double , Big Integer is slow in performance as internally BigInteger requires more number of operators for processing. I recommend use of javadoc (http://docs.oracle.com/javase/1.5.0/docs/api/java/math/BigDecimal.html).
Using BigInteger is also necessary when performing numerical calculations with large integers for e.g. Cryptographic purposes. The rounding used on floats or doubles would make applying the theories underlying these Cryptographic methods impossible.
I have two BigIntegers holding prime numbers.
BigInteger a = BigInteger.probablePrime(16, new Random());
BigInteger b = BigInteger.probablePrime(16, new Random());
BigInteger c;
How would I find the co-prime of these two BigIntegers and store it in c;
Co-primality of integers a and b refers to the question of whether the gcd(a,b) = 1 or not. Java's BigInteger class provides the gcd method to compute this:
BigInteger c = a.gcd(b); // or equivalently b.gcd(a).
I am trying to implement either the Fermat, Miller-Rabin, or AKS algorithm in Java using the BigInteger class.
I think I have the Fermat test implemented except that the BigInteger class doesn't allow taking BigIntegers to the power of BigIntegers (one can only take BigIntegers to the power of primitive ints). Is there a way around this?
The problematic line is denoted in my code:
public static boolean fermatPrimalityTest(BigInteger n)
{
BigInteger a;
Random rand = new Random();
int maxIterations = 100000;
for (int i = 0; i < maxIterations; i++) {
a = new BigInteger(2048, rand);
// PROBLEM WITH a.pow(n) BECAUSE n IS NOT A BigInteger
boolean test = ((a.pow(n)).minus(BigInteger.ONE)).equals((BigInteger.ONE).mod(n));
if (!test)
return false;
}
return true;
}
I think BigInteger.modPow might be what you're looking for. Note the "mod m" in Fermat's test.
One of the primality tests is built into BigInteger.isProbablePrime(). Not sure which one, you'd have to look at the source.
Also, you can raise a number to a power by multiplying. For example: 2^100 = 2^50 * 2^50. So pull out pieces of your BigInteger power and loop until you've used it up. But are you sure you don't mean to use BigInteger.modPow(), which takes BigIntegers? It looks like you are, based on your test.
You'll have to implement your own pow() method. Look at the sources of BigInteger.pow() as a starting point.
I was wondering if there was a way to multiply BigInteger variables together, because the * operator cannot be applied to BigInteger.
So I was wondering if it was possible to multiply two BigIntegers together without using the * operator.
You use BigIntegers multiply() method like so:
BigInteger int1 = new BigInteger("131224324234234234234313");
BigInteger int2 = new BigInteger("13345663456346435648234313");
BigInteger result = int1.multiply(int2)
I should have pointed out a while ago that BigInteger is immutable. So any result of an operation has to be stored into a variable. The operator or operand are never changed.
Easier way to implement:
int i = 5;
BigInteger bigInt = new BigInteger("12345678901");
BigInteger result = bigInt.multiply(BigInteger.valueOf(i))
You can use the multiply(BigInteger) method in BigInteger. So:
BigInteger result = someBigInt.multiply(anotherBigInt);
BigInteger in Java API
The result multiplying these specific factors
A: 131224324234234234234313
B: 13345663456346435648234313
Could be this one (I hope I am correct):
R: 1751275668516575787795211751170772134115968581969
Both are considered being two positive integers. And the technique used
was Karatsuba’s method
int ab = (mul1) * 10^n + (mul3 - mul1 - mul2) * 10^n/2 + mul2;