[英]Why do it succeed to deal with the memory size of long data type like this?
I am new to dealing with very large integers in java, in regards to mathematical questions.关于数学问题,我是处理 java 中非常大的整数的新手。
This is my answer to a solution of cutting papers into 1*1 squares.这是我对将纸张切割成 1*1 正方形的解决方案的回答。
public static void main(String[] args) {
long result = solve(841251657, 841251657);
System.out.println(result);
}
static long solve(int n, int m) {
long r = n*m - 1;
return r;
}
The output is 1810315984
, which is far from the expected output of 707704350405245648
. output 为1810315984
,与预期的 output 707704350405245648
。
However, both ways below:但是,以下两种方式:
Either replacing the mathematical calculation for long
with BigInteger
,要么用BigInteger
代替long
的数学计算,
static long solve(int n, int m) {
BigInteger r = BigInteger.valueOf(n).multiply(BigInteger.valueOf(m));
return r.longValue() - 1;
}
Or inserting the input manually(not sure if it is the actual reason),或手动插入输入(不确定是否是实际原因),
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
long m = in.nextLong();
long n = in.nextLong();
long cuts = m*n-1;
System.out.println(cuts);
}
can both output the expected answer. output 都可以得到预期的答案。
It would be really nice if I could know the reasons.如果我能知道原因,那就太好了。 Thank you so much.太感谢了。
The value of n * m
is getting overflowed from int
limit and therefore you can cast one of n
or m
to long
in order to turn the result of the multiplication to long
. n * m
的值从int
limit 溢出,因此您可以将n
或m
之一转换为long
,以便将乘法的结果转换为long
。
public class Main {
public static void main(String[] args) {
long result = solve(841251657, 841251657);
System.out.println(result);
}
static long solve(int n, int m) {
long r = (long)n * m - 1;
return r;
}
}
Output: Output:
707704350405245648
It's important for you to know that when the value of an int
overflows, it starts again from its minimum limit eg重要的是要知道,当int
的值溢出时,它会从其最小限制重新开始,例如
public class Main {
public static void main(String[] args) {
int x = Integer.MIN_VALUE;
System.out.println(Integer.MIN_VALUE);
System.out.println(x + 1);
System.out.println(x + 2);
}
}
Output: Output:
-2147483648
-2147483647
-2147483646
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.