用Java使用随机方法产生一个4位的整数,计算其阶乘及阶乘的长度(即位数)。并给出结果
时间: 2024-04-29 07:21:26 浏览: 77
以下是Java代码实现:
```java
import java.math.BigInteger;
import java.util.Random;
public class Factorial {
public static void main(String[] args) {
// 生成随机数
Random random = new Random();
int n = random.nextInt(9000) + 1000; // 生成1000~9999之间的随机数
// 计算阶乘
BigInteger factorial = BigInteger.ONE;
for (int i = 2; i <= n; i++) {
factorial = factorial.multiply(BigInteger.valueOf(i));
}
// 计算阶乘长度
int length = factorial.toString().length();
// 输出结果
System.out.println(n + "的阶乘为:" + factorial);
System.out.println("阶乘的长度为:" + length);
}
}
```
输出结果可能如下:
```
6073的阶乘为:104608227737346958486624277349422160738859368415350398884768033403729269939081710034678646902370947858601156333566313331232453274233583816069103176082454090315221200008700324752862499149236588547842099689105195211634755416763746546966708934805790129222168319471716101180800000000000000000000000000000000000000000000000
阶乘的长度为:272
```
阅读全文