I'm trying to make a program that converts values to bits. Everything worked well till I got to GB(gigabytes). So for instance 1 GB should equal 8 billion bits but the result is giving me a negative answer. Here is my code can someone give me some insight?
else if(line.equals("GB")) {
Scanner num = new Scanner(System.in);
System.out.println("How many GigaBytes are you transfering to bits?");
int number = num.nextInt();
//int ans = number * 8 * 1000000000;
BigInteger bigAns = BigInteger.valueOf(number * 8 * 1000000000);
System.out.println(number + " GigaByte(s) equals " + bigAns + " bits.");
}
Here is the output I'm getting: 1 GigaByte(s) equals -589934592 bits.
It wouldn't be a bad thing to use BigInteger throughout your calculations. This way, you don't run the risk of overflow while multiplying these numbers.
BigInteger bigAns = BigInteger.valueOf(number).multiply(BigInteger.valueOf(8))
.multiply(BigInteger.valueOf(1000000000L));
You are getting a negative number because you are exceeding the maximum possible value for a signed 32bit integer and causing an overflow.
When dealing with large numbers like this, you should use long instead, which is capable of holding much larger numbers.
To implement this, change int ans = number * 8 * 1000000000 tolong ans = number * 8 * 1000000000l
The answer you get is a garbage value.
You can convert int to BigInteger by doing so:
BigInteger bi = BigInteger.valueOf(myInteger.intValue());
And as Bohsulav said:
You can use this number * 8 * 1000000000l to prevent the overflow.
Helped? Let me know :)
First convert to biginteger then perform the computations.
BigInteger.valueOf(number * 8 * 1000000000);
Here, you perform the computation in int, then convert to BigInteger afterwards, when it is too late.
Use BigInteger.valueOf(number), then call appropriate methods to perform your computation.
Related
I was solving a problem and the basic idea to calculate the power of 2 for some k. And then multiply it with 10. Result should be calculated value mod
10^9+7.
Given Constraints 1≤K≤10^9
I am using java language for this. I used 'Math.pow' function but 2^10000000 exceeds its range and I don't want to use 'BigInteger' here. Any other way to calculate such large values.
The actual problem is:
For each valid i, the sign with number i had the integer i written on one side and 10K−i−1 written on the other side.
Now, Marichka is wondering — how many road signs have exactly two distinct decimal digits written on them (on both sides in total)? Since this number may be large, compute it modulo 10^9+7.
I'm using this pow approach, but this is not an efficient way. Any suggestion to solve this problem.
My original Solution:
/* package codechef; // don't place package name! */
import java.util.*;
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
while(t-->0){
long k = scan.nextInt();
long mul=10*(long)Math.pow(2, k-1);
long ans = mul%1000000007;
System.out.println(ans);
}
}
}
After taking some example, I reached that this pow solution works fine for small constraints but not for large.
while(t-->0){
long k = scan.nextInt();
long mul=10*(long)Math.pow(2, k);
long ans = mul%1000000007;
System.out.println(ans);
}
This pow function is exceeding its range. Any good solution to this.
Basically, f(g(x)) mod M is the same as f(g(x) mod M) mod M. As exponentiation is just a lot of multiplication, you can just decompose your single exponentiation into many multiplications, and apply modulo at every step. i.e.
10 * 2^5 mod 13
is the same as
10
* 2 mod 13
* 2 mod 13
* 2 mod 13
* 2 mod 13
* 2 mod 13
You can compact the loop by not breaking up the exponentiation so far; i.e. this would give the same answer, again:
10
* 4 mod 13
* 4 mod 13
* 2 mod 13
Faruk's recursive solution shows an elegant way to do this.
You need to use the idea of dividing the power by 2.
long bigmod(long p,long e,long M) {
if(e==0)
return 1;
if(e%2==0) {
long t=bigmod(p,e/2,M);
return (t*t)%M;
}
return (bigmod(p,e-1,M)*p)%M;
}
while(t-->0){
long k = scan.nextInt();
long ans = bigmod(2, k, 1000000007);
System.out.println(ans);
}
You can get details about the idea from here: https://www.geeksforgeeks.org/how-to-avoid-overflow-in-modular-multiplication/
As the size of long is 8 bytes and it is signed datatype so the range of long datatype is -(2^63) to (2^63 - 1). Hence to store 2^100 you have to use another datatype.
Why is the following code is not giving expected output even though it works for some small inputs? Here I am expecting the sum of all integers in the range between "a" and "b". Is the logic used wrong or are some other things wrong?
class RangeSum {
public static void main(String args[] ){
// BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
long i = Long.valueOf("99");
long j = Long.valueOf("1000000000000");
long ans = 0L;
/*if(i<0 || i>Math.pow(10, 18)){
//throw new Exception("Wroong Input.");
}
if(i<0 || i>Math.pow(10, 18)){
//throw new Exception("Wroong Input.");
}*/
if (j>i){
long sumTill_j = (j*(j+1))/2;
long sumTill_i = ((i-1)*i)/2;
ans = sumTill_j - sumTill_i;
System.out.println(ans);
}else{
long sumTill_i = (i*(i+1))/2;
long sumTill_j = ((j-1)*j)/2;
ans = sumTill_i - sumTill_j;
System.out.println(ans);
}
}
}
The largest possible number that you can represent in a long is 263 - 1, which is about 9.2 x 1018. If your calculation exceeds that, then the calculation will overflow without any exceptions being thrown and you will get the wrong answer.
In your case:
1,000,000,000,000 * (1,000,000,000,000 + 1) / 2
is about 5 x 1023 if my mental arithmetic is correct. That will overflow.
Solution: use BigInteger.
This is the result of integer overflow. What this means is, even though you're using the largest primitive you can (long), the value you're trying to calculate exceeds the maximum representable value.
A long can only store a value that is 263-1, which is around 9 quintillion, or 9.22 * 1018. The value that you're trying to generate from your sum exceeds that value with a difference of around 499 sextillion.
Don't fret; you can still calculate this insanely large value, but you have to make a few changes, notably, you can no longer use long. Move to BigInteger instead.
You can't use any of the primitive operators instead, but you can call functions which you would expect to be available, such as add, subtract, multiply, and divide.
Here is the first part of the code converted to use it; I leave the other half as an exercise for the reader.
BigInteger i = BigInteger.valueOf(99L);
BigInteger j = BigInteger.valueOf(1000000000000L);
BigInteger ans = BigInteger.ZERO;
if (j.compareTo(i) > 0) {
BigInteger sumTill_j = (j.multiply(j.add(BigInteger.ONE))).divide(BigInteger.valueOf(2L));
BigInteger sumTill_i = ((i.subtract(BigInteger.ONE)).multiply(i)).divide(BigInteger.valueOf(2L));
ans = sumTill_j.subtract(sumTill_i);
System.out.println(ans);
}
1000000000000 = 0xE8D4A51000 which needs at least 40 bits to store. Therefore multiplying j by j+1 needs an 80-bit type to store. The result is overflowing long type as it has only 64 bits. If you really want to do that the only way is using a bigint type like BigInteger
Btw why don't just use 99L and 1000000000000L? Calling valueOf is just redundant and slow
long i = Long.valueOf("99");
long j = Long.valueOf("1000000000000");
In short: j * (j + 1) gets overflow when j = 1,000,000,000,000.
Java's signed long has 64 bits, which has 2^63 - 1 or 9,223,372,036,854,775,807 as the maximum value.
Your integers are too high in value. Try using another type of integer instead, as it will help those larger values. Here is a good website that explains BigInteger in detail: http://www.tutorialspoint.com/java/math/java_math_biginteger.htm
I am trying to solve the following problem
you should calculate the difference between the square of the sum of the first n integers and the sum of the squares of the first n integer.
When I enter a large number (e.g. 4094574264) the answer is negative. Why? It should be a positive number.
Scanner scan = new Scanner(System.in);
long input = scan.nextLong();
long answer = (input * (input + 1) / 2)*(input * (input + 1) / 2) - (input * (input + 1)) * ((input * 2) + 1) / 6;
System.out.println(answer);
The problem is in this line
(input * (input + 1) / 2)*(input * (input + 1) / 2) - (input * (input + 1)) * ((input * 2) + 1) / 6
4094574264 is a 33-bit signed number, therefore input * (input + 1) will need 66 bits to store, which overflows 64-bit long. That's not counting the series of multiplications later, resulting in a result much larger than 64 bits.
If you want to do such high precision arithmetic, use BigInteger instead
You, my friend, are experiencing overflow. This is when there aren't enough bits to describe the number that you want to explain, so you end up going around in a big loop (hence the negative numbers).
The solution, if you wish to use incredibly large numbers, is to use the BigInteger and BigDecimal class. These are designed to create arbitrary precision numbers.
Low-level answer:
The answer is negative because you're experiencing overflow. The JVM can only represent numbers up to a certain value (the maximum for that type.) If you perform any operation which increases a value beyond the maximum, it "flows over" the machine's representation capabilities and changes the number completely; in your case, to a negative value. The opposite applies to negatives: if I decrease a negative value below the minimum, it will "flow under" and I will get an answer that is a very large positive. Use BigInteger (https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html) for "large math."
Sorry im new to java, currently i wanted to code the value to next thousand instead of nearest thousand. But i have no ideas how to do it. I tried Math.round but it's for roundest. Please guide me, any help would be appreciated .
Expected output that i looking for :
example 1) if the place values less than 999, it will direct change to 1000
May i know how can i code the math formula for this ?
You can use Math.ceil for this.
// A quick code example :)
int val = 1400;
val = (int) (Math.ceil(val / 1000.0) * 1000);
You need to write some custom code as follow
int leftdigit=value/1000;
int nextthousand=(leftdigit+1)*1000;
Here Kindly note Math.ceil returns double so you should use it properly as stated below as for integer value it won't work properly and integer division will be performed.
double data = 1100;
data = Math.ceil(data / 1000) * 1000;
System.out.println(data);
OUTPUT
2000.0
Conversion from integers to floats leads to chaos, as for the same bit size, float mantissa length will always be smaller than integer size (IEEE-754 float mantissa is 23 bits vs 31 bits for the integer). Converting a large integer to float back and forth will not give the same integer after the conversion.
So here using Math.ceil() may work for integers or small long ints, but will break for large long values (63 bits).
Better use the following code (only works for value > 0):
int ii = ((i - 1) / 1000 + 1) * 1000;
or for long int version:
long ii = ((i - 1) / 1000 + 1) * 1000;
Does not unnecessarily overflow, keep precision even for large values, and probably way faster!
Addenda
As an example, the following java code:
int largeint = Integer.MAX_VALUE - 63;
float fl = (float)largeint;
int largeint2 = (int)fl;
System.out.println(largeint);
System.out.println(largeint2);
Print:
2147483584
2147483647
I was doing some stuff with palindromes:
This number 9966006699 has been giving me problems. It's a product of 99979 and 99681
99979 * 99681 = 9966006699
I ran that in PHP
$i = 99979 * 99681;
echo $i;
var_dump($i);
Outputs
9966006699 float(9966006699)
So in PHP the product is obviously a float data type. But in Java it's different as seen below :
This
public static void main(String[] args) {
float f = 99979 * 99681;
System.out.println(f);
long o = 99979 * 99681;
System.out.println(o);
double d = 99979 * 99681;
System.out.println(d);
int i = 99979 * 99681;
System.out.println(i);
}
Outputs
1.37607206E9
1376072107
1.376072107E9
1376072107
Google's calculator gives the right thing
I'm lost, why is Java giving the wrong output? and Does it have anything to do with the E9 stuff behind the float and double types? Help. Thanks
The numbers 99979 and 99681 are both int's. The multiplication expression is therefore an int expression too. The maximum value of an int expression is 2147...... Your value 9966006699 is way above that. Hence you have fallen in the realms of the strange behaviour that you get from modulo-n arithmetic. (That is, you have fallen victim to the C-family languages' version of the Y2K problem.)
Try this :
long o = (long)99979 * 99681;
System.out.println(o);
It looks like integer overflow as 9 966 006 699 > Integer.MAX_INT = 2 147 483 647. As int times int have type int the result overflows. Then it is cast to int/float/long etc.
This should be correct (for non-int):
long value = (long)99979 * (long)99681
Alternativly you can use BigInteger class which:
May be slower the using int/long
Don't have this problem for any numbers (long just moves the problem from 2^31 - 1 to 2^63-1).
Integer.MAX_VALUE is equal to 2^31-1, which is smaller than the number you're dealing with, so you're essentially getting integer overflow issues. You can get around this by using a long, or the BigInteger class.
You can read about the numeric limits of primitive data types here:
http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html