Stack Overflow Asked by VMS on December 26, 2020
whenever I give x =2 and y>5 the result is zero. for any other value it’s ok..
package forLoopquestionsForForLoop;
import java.util.Scanner;
public class CalculatexXPowerY {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("enter X");
long x = sc.nextInt();
System.out.println("enter y");
long y = sc.nextInt();
int power = 1;
for(int i =0;i<y;i++) {
x *= x;
}
System.out.println(x);
}
}
Have some time, so I figured I'd come back and give a more proper explanation of what is happening. Your long
variable is represented in the system as a series of bits, 64 of them in fact, which can contain either 0 or 1 as their value. They can be visualized like so:
0000 0000 0000 0010 0000 0000 1100 0000 0000 0000 0001 0000 0000 0000 0000 0100
Having all 0's translates to the value zero and the front most bit is reserved for special usage as a marker for whether the number is positive or negative. This means the maximum positive value you can have is 2^63-1 which ~9.22 e+18.
Now, when you multiply these bits they essentially shift over a certain number of spots before adding themselves. This can lead to unexpected behavior called overflow which pushes the calculated value over the maximum size of it's variable container. When this happens, the system can no longer track the bits that exceed the sequence and essentially "forgets" about them. Lets look at a 4 bit example:
1111 (15)
x 0011 (3)
---------
1111 (15)
+ 11110 (30)
+ 000000 (0)
+ 0000000 (0)
---------
0101101 (45)
The value 0101101
exceeds our 4 bits though, so the system "forgets" about the bits that exceed the 4 and turns into 1101
instead. This is what is happening with your zeroing out problem. Yours is an interesting case though because with the value 4294967296
you're essentially performing:
0000 0000 0000 0000 0000 0000 0000 0001 0000 0000 0000 0000 0000 0000 0000 0000
x 0000 0000 0000 0000 0000 0000 0000 0001 0000 0000 0000 0000 0000 0000 0000 0000
-----------------------------------------------------------------------------------
1 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000
And then because the foremost 1
is greater than the maximum bits for a long
it is "forgot" which leaves only 0
as the value. After that, every multiplication is doing 0 x 0
over and over. Hope this answers your question more completely.
Correct answer by Tim Hunter on December 26, 2020
You are exceeding the max value of Long, when you assign values x = 2 and y > 5. You can use BigInteger instead.
import java.math.BigInteger;
BigInteger result = new BigInteger("1");
for(int i =0;i<y;i++)
{
result = result.multiply(BigInteger.valueOf(x));
}
System.out.println(result);
}
Answered by Sagar Das on December 26, 2020
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP