package test.leecode.math;

import java.math.BigInteger;

/**

* int*int,long*long,都可能溢出

* @author wen.lei@brgroup.com

*

* 2022-3-18

*/

public class IntMultiplyIntTest {

public static void main(String[] args) {

System.out.println("Integer的最大值:"+Integer.MAX_VALUE);

System.out.println("Long的最大值:"+Long.MAX_VALUE);

System.out.println("大数相乘,需要用BigInteger:"+new BigInteger("60070").multiply(new BigInteger("60070")));

System.out.println("大数相乘,用BigInteger封装的方法:"+big(60070));

System.out.println("大数相乘,用int*int会溢出:"+60070 * 60070);

System.out.println("小数相乘,用int*int不溢出:"+6007 * 6007);



}



public static BigInteger big(int k) {

return new BigInteger(String.valueOf(k)).multiply(new BigInteger(String.valueOf(k)));

}



//输入类型为long,可以支持更大的k;但是如果k太大,也会溢出

public long test1(long k) {

//int的最大值也太小了,2147483647,2个万相乘就是亿了

return (1 + k) * k / 2;

}



//返回值用long,也会越界

public long test2(int k) {

return (1 + k) * k / 2;

}



//越界了

public int test3(int k) {

//int的最大值也太小了,2147483647,2个万相乘就是亿了

return (1 + k) * k / 2;

}

}