‘壹’ java中怎么实现阶乘,如计算1~100的阶乘
使用BigInteger大容量运算类计算100的阶乘
一.一般算法(循环)
view plain to clipboardprint?
public class Test {
public static void main(String[] args) {
int result = 1;
for (int i = 1; i <= 100; i++) {
result *= i;
}
System.out.println(result);
}
}
public class Test {
public static void main(String[] args) {
int result = 1;
for (int i = 1; i <= 100; i++) {
result *= i;
}
System.out.println(result);
}
}
输出结果为0,因为int无法保存下100的阶乘的结果,100的阶乘的长度至少大于50位,也要大于long,double
二.使用BigInteger大容量运算类
view plain to clipboardprint?
import java.math.BigInteger;
public class Test {
public static void main(String[] args) {
BigInteger result = new BigInteger("1");//为result赋初始值,为1
for (int i = 1; i <= 100; i++) {
BigInteger num = new BigInteger(String.valueOf(i));
result = result.multiply(num);//调用自乘方法
}
System.out.println(result);//输出结果
System.out.println(String.valueOf(result).length());//输出长度
}
}
import java.math.BigInteger;
public class Test {
public static void main(String[] args) {
BigInteger result = new BigInteger("1");//为result赋初始值,为1
for (int i = 1; i <= 100; i++) {
BigInteger num = new BigInteger(String.valueOf(i));
result = result.multiply(num);//调用自乘方法
}
System.out.println(result);//输出结果
System.out.println(String.valueOf(result).length());//输出长度
}
}
计算结果为:000000000000000000
产度:158