壹.壹般算法(循環)
view plaincopy 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 plaincopy 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());//輸出長度
}
}
計算結果為:93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
產度:158