今天在做一道计算n个a相减的题目时,发现用上long数据仍然会溢出,可是Java中又没有long long,于是查询后发现可以引入BigInteger来实现对超大数据的处理,题目如下:
【问题描述】
输入两个整数a(大于等于1且小于等于9)和n(大于等于1且小于等于80),编程求得并输出下面等式的值:
例如:若输入的a为5,n为6,则要计算下面公式的值:
555555-55555-5555-555-55-5。
【输入形式】
从标准输入读入整数a和n,两者之间以一个空格分隔。
【输出形式】
在标准输出上输出公式的计算结果。
【样例1输入】
5 6
【样例1输出】
493830
【样例1说明】
输入的a为5,n为6,按照上述公式计算的结果为493830。
【样例2输入】
5 20
【样例2输出】
49382716049382716060
【样例2说明】
输入的a为5,n为20,按照上述公式计算的结果为49382716049382716060。
【评分标准】该程序要求输出求得的公式的值。
这道题的实现思路不难,便不多赘述:
import java.util.Scanner;
import java.math.BigInteger;
public class everydayjava {
public static BigInteger fun(long a, long n) {
if (a < 1 || a > 9 || n < 1 || n > 80)
return BigInteger.valueOf(-1);
BigInteger r = BigInteger.valueOf(0);
BigInteger ans;
for (long i = 0; i < n; i++) {
r = r.multiply(BigInteger.TEN).add(BigInteger.valueOf(a));
}
ans = r;
r = r.divide(BigInteger.TEN);//表示一个 BigInteger 对象,它等于整数值 10
while (r.compareTo(BigInteger.ZERO) > 0) {
ans = ans.subtract(r);
r = r.divide(BigInteger.TEN);
}
return ans;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
long a = scanner.nextInt();
long n = scanner.nextInt();
scanner.close();
BigInteger ans = fun(a, n);
System.out.println(ans);
}
}
下面讲一下BigInteger的具体用法
BigInteger的用法
BigInteger
是 Java 中的一个类,它用于处理任意精度的整数,不受限于固定的数据类型大小,因此可以表示非常大的整数,远远超出了 long
或 int
数据类型的范围。
1.创建 BigInteger
对象: 可以使用 BigInteger
的构造方法创建对象。有多种方法可以创建 BigInteger
对象,包括使用整数、字符串、字节数组等。
BigInteger bigInt1 = new BigInteger("1234567890123456789012345678901234567890");
BigInteger bigInt2 = BigInteger.valueOf(42);
2. 可以执行基本的算术操作(加、减、乘、除)以及比较操作(大于、小于、等于)等。
BigInteger sum = bigInt1.add(bigInt2);
BigInteger difference = bigInt1.subtract(bigInt2);
BigInteger product = bigInt1.multiply(bigInt2);
BigInteger quotient = bigInt1.divide(bigInt2);
boolean isEqual = bigInt1.equals(bigInt2);
3.还可以进行取模、取幂、获取绝对值、比较、转换为字符串等操作。
BigInteger remainder = bigInt1.mod(bigInt2);
BigInteger power = bigInt1.pow(3);
BigInteger absValue = bigInt1.abs();
int comparison = bigInt1.compareTo(bigInt2);
String strValue = bigInt1.toString();
4.不可变性: BigInteger
是不可变的,这意味着一旦创建了一个 BigInteger
对象,它的值就不能被更改。每次执行算术操作都会创建一个新的 BigInteger
对象来存储结果。
BigInteger original = new BigInteger("10");
BigInteger modified = original.add(new BigInteger("5"));
System.out.println(original); // 输出 10
System.out.println(modified); // 输出 15
5.处理大整数: BigInteger
在处理大整数时非常有用,例如大数学运算、密码学等领域。由于它的不可变性,你可以安全地进行操作,而不必担心数据丢失或溢出。
import java.math.BigInteger;
public class BigIntegerExample {
public static void main(String[] args) {
BigInteger bigInt1 = new BigInteger("1234567890123456789012345678901234567890");
BigInteger bigInt2 = BigInteger.valueOf(42);
BigInteger sum = bigInt1.add(bigInt2);
BigInteger product = bigInt1.multiply(bigInt2);
System.out.println("Sum: " + sum);
System.out.println("Product: " + product);
}
}