Mayank SAssociate Director - Product EngineeringCommented:
You will have to make the assumption that the BigInteger value holds something which is not greater than the range of long and optimistically use longValue (). Though I don't think that this would help in your case (if it was a value within the range of long that you wanted to store, why would you use a BigInteger in the first place?).
By the way, you might be better of converting the result of Math.pow () into a BigInteger and using the remainder () method provided by the BigInteger class.
I assumed that x3 BigInteger was given to him (argument or someting like that).
If x3 may hold values bigger then long (which actually I doubt that is the case for a module value) then Yes you can take
the approach of using only BigInteger calculation.
somethig like that:
BigInteger result = new BigInteger(x1).modPow(new BigInteger(x2). x3);
you can always call result.longValue() or result.intValue()
Mayank SAssociate Director - Product EngineeringCommented:
>> would there a difference stroing my integer as long?
Why are you using a BigInteger in the first place? Perhaps because the values are very large?
>> how do I declare it as a long interger?
long x3 ; // just like any other variable-declaration - but do that only if you know that the value will fit in it
>> the value input would be a very large value
If it is bigger than a 'long', then you should use BigInteger the way you are using. And if it will always be a positive value, then you could use the remainder () method as I had shown.
Right, sorry BigInteger doesn't accept integer in the constuctor (but does accept string).
See that:
import java.math.*;
public class Tmp
{
public static void main(String st[]) throws Exception
{
int x1 = 12;
int x2 = 2;
BigInteger x3 = new BigInteger("5");
BigInteger result = new BigInteger(String.valueOf(x1)).modPow(new BigInteger(String.valueOf(x2)), x3);
System.out.println(result);
}
}
x.modPow(y,z) is doing exactly: (x ^ y) % z
or in words: (x power y) mod z.
It is added to the JDK because it is a common thing to do in cryptography.
If you look at BigInteger API you see many other related methods (like isPrime ....)
0
yongengAuthor Commented:
thanxs aozarov..... you have been a great help :)
would like to consult you on one last question on this topic.....
I tried to modify your statement to calculate ((x ^ y)*a) % z
but I was prompted with the error that "operator * cannot be applied to bigInteger".... is there a work around?
public class Tmp
{
public static void main(String st[]) throws Exception
{
int x1 = 12;
int x2 = 2;
BigInteger x3 = new BigInteger("5");
BigInteger result = new BigInteger(String.valueOf(x1)).modPow(new BigInteger(String.valueOf(x2)), x3);
System.out.println(result);
int a = 2;
result = new BigInteger(String.valueOf(x1)).pow(x2).multiply(new BigInteger(String.valueOf(a))).mod(x3);
System.out.println(result);
}
}
% x3.doubleValue();