/** * Title: Demo02_累加累乘运算.java * @author Mr.Seven * @date 2020年9月3日 * @version 1.0 */ package cn.tedu.day903; //用Biginteger实现任意起始位置结束位置累加、累乘的结果。
//比如,从20到50的阶乘值为250023166568122405335142878324631535616000000000
//1到100累乘值为93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
import java.math.BigInteger;
import java.util.Scanner;
public class Demo02_累加累乘运算 {
public static void main(String[] args) {
System.out.println("请输入累加(累乘)起始值:"); Scanner sc1 = new Scanner(System.in); long start = sc1.nextInt();
System.out.println("请输入累加(累乘)结束值:"); Scanner sc2 = new Scanner(System.in); long end = sc2.nextInt();
long sum = 0; BigInteger s1 = new BigInteger("1");// 令初始阶乘值为1 BigInteger s2 = BigInteger.valueOf(start);// 将起始阶乘值long类型转赋值给大类型s2
// 累加 for (long i = start; i <= end; i++) { sum = sum + i; }
for (long j = start; j <= end; j++) {// 阶乘循环运算 s1 = s1.multiply(s2); s2 = s2.add(new BigInteger("1"));
}
System.out.println("累加值为:" + sum + "\n" + "累乘值为:" + s1); sc1.close(); sc2.close(); }
}