How do i store numbers bigger than 10 billion - java

I am making a program and i need a way to make variables go over 10 billion and int only stores up to 999 million for me so i decided to use a long instead of a int and it turn out it only stores up to 999 million as well.
int TotalWorldPop = 7200000000;
gives me the "literal is out of range" error
long TotalWorldPop = 7200000000;
gives me the "literal is out of range" error as well
but
int TotalWorldPop = 999999999
is ok for me

A long can accommodate numbers as large as 263-1. But there's a trick to putting them into the primitive field.
If you're entering the primitive literal, then you have to add an L at the end, as all numeric literals are treated as int (and it can only go up to ~2.1 billion).
If you need numbers larger than that, use BigInteger.

You could use a BigInteger to store very large numbers.
Example:
Biginteger bigInt1 = new Biginteger("91826581752671985235272769716");
Biginteger bigInt2 = new Biginteger("-1796357891266373473772242");
Biginteger bigint3 = bigInt1.divide(bigInt2);
Biginteger bigint4 = bigInt1.add(bigInt2);

Related

Converting Long number to byte array

I am trying to convert a long number (convertex from Hex to Long) to a byte array. I'm trying the following code:
ByteBuffer b = ByteBuffer.allocate(4);
// The literal 4328719365 of type int is out of range
b.putLong(4328719365);
byte[] result = b.array();
but it's not compiling due to being out of range for int.
What can I do to solve this issue?
Suffix L (or l) converts literal number to a long.
So try this:
b.putLong(4328719365L);
You can use literal long value just like number without L suffix. Like assign them to variables:
long myLongValue = 4328719365L;
b.putLong(myLongValue);
1) Suffix L to the value
2) Increase the ByteBuffer allocated size and try
3) Int will take max of 10 digits and putLong might internally add L and making it beyond 10. Please check reducing digits in number.

long to int conversion in java not working

I am working on a problem with big number's in java.
int temp =0;
long last = 218212982912L;
temp = (int) last%10;
last = last/10;
for the above line of code I get the
temp = -4
in the first iteration. I am not sure what is the problem. I have tried a lot of solution online available.
Put parentheses around last%10
The cast to int is being applied before the modulus operation
The last positive you can get is 2,147,483,647 and when you are explicitly converting a larger number to int, your will get unpleasant results but if you put extra parentheses like (int) (someLong % 10), first the long operation get executed (which results in smaller long value that fits int memory space) and then you can cast it to int without worry

Trouble integer parsing two simple strings

I'm having trouble integer parsing 2 strings, and concatenating the contained integers. I find when the integer to be parsed exceeds 5 characters in length, when the button is clicked the program/app crashes.
What can I do to fix this? (to make it work with integers exceeding 5 chars in length)
Code:
public void SimpleButton (View V){
int ab = 123456;
int abc = 223456;
int a = Integer.parseInt(Integer.toString(ab) + Integer.toString(abc));
Toast.makeText(getBaseContext(), String.valueOf(a), Toast.LENGTH_LONG).show();
}
The MAX_VALUE of integer is 2,147,483,647 however when you concatenate the String values you are getting the number 123,456,223,456 which is much larger than the max value for an integer. You must use a Long.
long a = Long.parseLong(Integer.toString(ab) + Integer.toString(abc));
When you concatenate the String forms of the two numbers together, you get a 12-digit number, which is too large to store in an int. The maximum is about 2.1 billion, a 10-digit number. The constant Integer.MAX_VALUE is the maximum possible int, 2147483647.
Parse a long with Long.parseLong, which can handle larger numbers (or reduce the number of digits in ab and/or abc). The constant Long.MAX_VALUE is the maximum possible long, 9223372036854775807L, which is 19 digits.
long a = Long.parseLong(Integer.toString(ab) + Integer.toString(abc));

Number at f(93) in fibonacci series has negative value, how?

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);

Java parsing long from string

I'm currently trying to parse some long values stored as Strings in java, the problem I have is this:
String test = "fffff8000261e000"
long number = Long.parseLong(test, 16);
This throws a NumberFormatException:
java.lang.NumberFormatException: For input string: "fffff8000261e000"
However, if I knock the first 'f' off the string, it parses it fine.
I'm guessing this is because the number is large and what I'd normally do is put an 'L' on the end of the long to fix that problem. I can't however work out the best way of doing that when parsing a long from a string.
Can anyone offer any advice?
Thanks
There's two different ways of answering your question, depending on exactly what sort of behavior you're really looking for.
Answer #1: As other people have pointed out, your string (interpreted as a positive hexadecimal integer) is too big for the Java long type. So if you really need (positive) integers that big, then you'll need to use a different type, perhaps java.math.BigInteger, which also has a constructor taking a String and a radix.
Answer #2: I wonder, though, if your string represents the "raw" bytes of the long. In your example it would represent a negative number. If that's the case, then Java's built-in long parser doesn't handle values where the high bit is set (i.e. where the first digit of a 16 digit string is greater than 7).
If you're in case #2, then here is one (pretty inefficient) way of handling it:
String test = "fffff8000261e000";
long number = new java.math.BigInteger(test, 16).longValue();
which produces the value -8796053053440. (If your string is more than 16 hex digits long, it would silently drop any higher bits.)
If efficiency is a concern, you could write your own bit-twiddling routine that takes the hex digits off the end of the string two at a time, perhaps building a byte array, then converting to long. Some similar code is here:
How to convert a Java Long to byte[] for Cassandra?
The primitive long variable can hold values in the range from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 inclusive.
The calculation shows that fffff8000261e000 hexademical is 18,446,735,277,656,498,176 decimal, which is obviously out of bounds. Instead, fffff8000261e000 hexademical is 1,152,912,708,553,793,536 decimal, which is as obviously within bounds.
As everybody here proposed, use BigInteger to account for such cases. For example, BigInteger bi = new BigInteger("fffff8000261e000", 16); will solve your problem. Also, new java.math.BigInteger("fffff8000261e000", 16).toString() will yield 18446735277656498176 exactly.
The number you are parsing is too large to fit in a java Long. Adding an L wouldn't help. If Long had been an unsigned data type, it would have fit.
One way to cope is to divide the string in two parts and then use bit shift when adding them together:
String s= "fffff8000261e000";
long number;
long n1, n2;
if (s.length() < 16) {
number = Long.parseLong(s, 16);
}
else {
String s1 = s.substring(0, 1);
String s2 = s.substring(1, s.length());
n1=Long.parseLong(s1, 16) << (4 * s2.length());
n2= Long.parseLong(s2, 16);
number = (Long.parseLong(s1, 16) << (4 * s2.length())) + Long.parseLong(s2, 16);
System.out.println( Long.toHexString(n1));
System.out.println( Long.toHexString(n2));
System.out.println( Long.toHexString(number));
}
Note:
If the number is bigger than Long.MAX_VALUE the resulting long will be a negative value, but the bit pattern will match the input.

Categories

Resources