编写一个Java 应用程序,计算两个大整数的和、差、积和商,并计算一个大整数的因 子个数(因子中不包括1 和大整数本身)。...
时间: 2024-02-25 08:55:04 浏览: 16
好的,这是一个计算器程序,可以计算两个大整数的和、差、积和商,并计算一个大整数的因子个数:
```java
import java.math.BigInteger;
import java.util.ArrayList;
public class Calculator {
public static void main(String[] args) {
BigInteger a = new BigInteger("12345678901234567890");
BigInteger b = new BigInteger("98765432109876543210");
// 计算和
BigInteger sum = a.add(b);
System.out.println("sum = " + sum);
// 计算差
BigInteger diff = a.subtract(b);
System.out.println("diff = " + diff);
// 计算积
BigInteger product = a.multiply(b);
System.out.println("product = " + product);
// 计算商
BigInteger quotient = a.divide(b);
System.out.println("quotient = " + quotient);
// 计算因子个数
ArrayList<BigInteger> factors = getFactors(a);
int factorCount = factors.size();
System.out.println("factorCount = " + factorCount);
}
public static ArrayList<BigInteger> getFactors(BigInteger n) {
ArrayList<BigInteger> factors = new ArrayList<>();
BigInteger i = BigInteger.valueOf(2);
while (i.compareTo(n) <= 0) {
if (n.mod(i).equals(BigInteger.ZERO)) {
factors.add(i);
n = n.divide(i);
} else {
i = i.add(BigInteger.ONE);
}
}
return factors;
}
}
```
这个程序使用了Java的BigInteger类,可以处理非常大的整数。计算和、差、积和商使用了BigInteger类的add、subtract、multiply和divide方法。计算因子个数使用了一个简单的算法,首先从2开始往上试除,如果可以整除,就把这个因子加入列表中,并把n除以这个因子,重复这个过程直到n等于1。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)