Java如何取得一个大整数的各个因子及其个数
时间: 2023-11-28 19:48:38 浏览: 40
Java中可以使用BigInteger类来处理大整数。要取得一个大整数的各个因子及其个数,可以使用以下步骤:
1. 将大整数转化为BigInteger类型,例如:
```
BigInteger num = new BigInteger("12345678901234567890");
```
2. 定义一个ArrayList来存储因子,一个HashMap来存储每个因子出现的次数,例如:
```
ArrayList<BigInteger> factors = new ArrayList<>();
HashMap<BigInteger, Integer> countMap = new HashMap<>();
```
3. 使用一个循环找到所有的因子,并将它们添加到ArrayList中,例如:
```
for (BigInteger i = BigInteger.valueOf(1); i.compareTo(num) <= 0; i = i.add(BigInteger.ONE)) {
if (num.mod(i).equals(BigInteger.ZERO)) {
factors.add(i);
}
}
```
4. 遍历ArrayList,统计每个因子出现的次数并存储到HashMap中,例如:
```
for (BigInteger factor : factors) {
if (countMap.containsKey(factor)) {
countMap.put(factor, countMap.get(factor) + 1);
} else {
countMap.put(factor, 1);
}
}
```
完整代码如下:
```
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
public class Factor {
public static void main(String[] args) {
BigInteger num = new BigInteger("12345678901234567890");
ArrayList<BigInteger> factors = new ArrayList<>();
HashMap<BigInteger, Integer> countMap = new HashMap<>();
for (BigInteger i = BigInteger.valueOf(1); i.compareTo(num) <= 0; i = i.add(BigInteger.ONE)) {
if (num.mod(i).equals(BigInteger.ZERO)) {
factors.add(i);
}
}
for (BigInteger factor : factors) {
if (countMap.containsKey(factor)) {
countMap.put(factor, countMap.get(factor) + 1);
} else {
countMap.put(factor, 1);
}
}
for (BigInteger factor : countMap.keySet()) {
System.out.println(factor + " appears " + countMap.get(factor) + " times.");
}
}
}
```