I am trying to compare numbers that are so large that even BigIntegers cannot deal with them. My solution is to convert the numbers to Strings and use String comparison on them.
Will this work? I am not really sure how to implement something like this. I am just attempting to unit test an algorithm to produce the factorial of 1000 for a project Euler program that I am sucked into.
Your assumption is wrong.
BigInteger provides arbitrary precision, so it can definitely deal with numbers this big.
Try the following:
public class Main {
public static void main(String[] args) {
BigInteger thousand = BigInteger.valueOf(1000L);
for (int i = 999; i > 0; i--)
{
thousand = thousand.multiply(BigInteger.valueOf(i));
}
System.out.println(thousand.toString());
}
}
Related
I am trying to convert a SQL function into Groovy for usage in Elasticsearch, but I am stuck at this stage. Considering, I have never touched java or groovy in my life, what am I doing wrong?
CODE
public String convertFromBaseToBase(String str, int fromBase, int toBase) {
return Integer.toString(Integer.parseInt(str, fromBase), toBase);
}
output = convertFromBaseToBase("8f8f87878f8f8080", 16, 10);
System.out.print(output);
Taken from Convert from one base to another in Java
ERROR
java.lang.NumberFormatException: For input string: "8f8f87878f8f8080"
at java_lang_Integer$parseInt.call(Unknown Source)
at Script1.convertFromBaseToBase(Script1.groovy:2)
at Script1.run(Script1.groovy:5)
8f8f87878f8f8080 is a very big number (10344635885392199808 in decimal), and will not fit inside an Integer.
You will have to use BigInteger for such big numbers.
public static String convertFromBaseToBase (String str, int fromBase, int toBase){
return (new BigInteger(str, fromBase)).toString(toBase);
}
Working Code --> https://www.onlinegdb.com/B1mMEcKPX
BigInteger -->https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#toString(int)
I am trying to find the sum of the digits of the number 2^1000 and I am using Java BigInteger class for this. However, I could not make it real. Eventually, I get a 0 (zero) with the following code. What might be the problem?
Thanks...
After Kon's help I fixed the problem, but this time I get a wrong result. Can anyone see the problem with the algorithm?
public static void main(String []args) throws Exception
{
BigInteger big = BigInteger.valueOf(2).pow(1000);
BigInteger big2 = BigInteger.valueOf(0);
//System.out.println(big);
for(long i = 1; i<283; i++)
{
big2 = big2.add(big.mod(BigInteger.valueOf((long) Math.pow(10,i))).divide(BigInteger.valueOf((long)Math.pow(10,i-1))));
}
System.out.println(big2);
}
Trying to calculate each digit of BigInteger using mod is not very efficient, because of many method calls you are doing in the process. Instead you can simplify by doing the conversion to String and getting each digit straight away.
BigInteger big = BigInteger.valueOf(2).pow(1000);
String digits = big.toString();
int sum = 0;
for(int i = 0; i < digits.length(); i++) {
int digit = (int) (digits.charAt(i) - '0');
sum = sum + digit;
}
System.out.println(sum);
The BigInteger class is immutable, therefore you have to assign the result of the operation to the variable itself.
big2.add(big.mod(BigInteger.valueOf((long) Math.pow(10,i))).divide(BigInteger.valueOf((long)Math.pow(10,i-1))));
should become
big2 = big2.add(big.mod(BigInteger.valueOf((long) Math.pow(10,i))).divide(BigInteger.valueOf((long)Math.pow(10,i-1))));
For more on immutable objects in Java, please take a look at this documentation.
Also, although your question is not specifically about this, using hard coded literal values in your loops is very bad practice. You want to loop over each digit in the BigInteger 2^1000. Well, you could get the number of digits using something like big.toString().length().
I am making an application that involves a seed to generate a world and some games let you provide that seed with text. I'm wondering how would you 'convert' a string to an integer.
A simple way would be to use the ASCII values of all the characters and append them to a string which you would then parse to an integer, but that severely limits the size of the string. How would you be able to do this with a larger string?
EDIT: 64 bit not 32
I would just call String.hashcode(). The standard String.hashcode() function makes use of all characters in the target string and gives good dispersal.
The only thing I would question is whether 32 bits of seed is going to be enough. It might mean that your world generator could generate at most 232 different worlds.
Random seeds for Random can be at least 48-bit, ideally 64-bit. You can write your own hash code like this.
public static long hashFor(String s) {
long h = 0;
for(int i = 0; i < s.length(); i++)
h = h * 10191 + s.charAt(i);
return h;
}
The Standard way for converting a String to Integer is using Integer.parseInt(String);
You pass the string into this and it would convert the String to int. Try it and let me know!
How do I find the modulo (%) of two long values in Java? My code says 'Integer number too large' followed by the number I'm trying to mod. I tried casting it to a long but it didn't work. Do I have to convert it to a BigInteger and use the remainder method? Thanks.
The % operator does work for longs. It sounds like you may have forgotten to stick L at the end of a numeric literal, as in 123456789L. Can we see your code?
You can only have an integer up to 2 147 483 647. If you want to go bigger than that, say 3 billion, you must specify it to be a long
class Descartes {
public static void main(String[] args) {
long orig = Long.MAX_VALUE;
long mod = orig % 3000000000; // ERROR 3000000000 too big
long mod = orig % 3000000000L; // no error, specified as a long with the L
}
}
Keep in mind that you can use capital OR lowercase L, but it's advisable to use capital, since the lowercase looks remarkably similar to the number 1.
You can also try working with the BigInteger class which has a remainder() method that works similarly to %.
I'm trying to print a small double number like 6.67e-11, but using Double.toString() returns 0. What can I do to make it print 6.67e-11 (or something similar) instead?
Unable to reproduce:
public class Test {
public static void main(String args[])
{
double d = 6.67e-11;
System.out.println(Double.toString(d)); // Prints "6.67E-11"
}
}
IIRC, Double.toString() always returns a string which allows the exact value to be round-tripped using Double.parseDouble().
My guess is that you don't actually have a small value - that you have 0, due to some rounding errors in other operations.