难度
1.5
/
10
1.5/10
1.5/10
学会Java之后的第一题高精度
题意
输入
n
n
n
输出
S
=
1
!
+
2
!
+
⋯
+
n
!
S=1!+2!+\cdots+n!
S=1!+2!+⋯+n!
数据范围
n ≤ 50 n\le 50 n≤50
思路
n n n 比较大,高精度推荐用Java编写。
相关高精度代码:
【0】读入一个高精度大数
BigInteger s1 = read.nextBigInteger();
System.out.println(s1);
【1】创建一个 “abc”(范围较大) 的高精度大数(静态):
BigInteger t = new BigInteger("112233445566778899");
【2】创建一个 “abc”(范围较大) 的高精度大数(动态):
String s = read.next();
BigInteger t = new BigInteger(s);
【3】创建一个abc(范围较小) 的高精度大数(静态)
BigInteger t = BigInteger.valueOf(120000000); /// 不能很大
【4】创建一个 abc(范围较小) 的高精度大数(动态):
int s = read.nextInt();
BigInteger t = new BigInteger("0" + s); /// 创建了一个对象,所以慢一些
BigInteger t = BigInteger.valueOf(s); /// 更快
【5】高精度大数加减乘除操作
Scanner read = new Scanner(System.in);
BigInteger s1 = read.nextBigInteger();
BigInteger s2 = read.nextBigInteger();
System.out.println(s1);
System.out.println(s2);
System.out.println(s1.add(s2));
System.out.println(s1.subtract(s2));
System.out.println(s1.multiply(s2));
System.out.println(s1.divide(s2));
直接输出和加减乘除的效果:
(注意这里的除法是整除)
【6】高精度大数绝对值/取模/取余/求gcd/求幂/比较函数
Scanner read = new Scanner(System.in);
BigInteger s1 = read.nextBigInteger();
BigInteger s2 = read.nextBigInteger();
System.out.println(s1);
System.out.println(s2);
System.out.println(s1.abs());
System.out.println(s1.mod(s2));
System.out.println(s1.gcd(s2));
System.out.println(s1.remainder(s2));
int shu = 5;
System.out.println(s1.pow(shu));
System.out.println(s1.compareTo(s2));
System.out.println(s1.equals(s2));
- 注意pow函数的参数要是int类型的
【7】高精度浮点数的读入与两种输出
Scanner read = new Scanner(System.in);
BigDecimal s1 = read.nextBigDecimal();
System.out.println(s1); /// 直接输出
System.out.println(s1.doubleValue()); /// 输出它的double类型的数据
【8】高精度浮点数的基本运算
- 加减乘除基本相同
- 判断连个高精度浮点数是否相同时,使用compareTo()函数,不能使用equals()函数
- 除法:
Scanner read = new Scanner(System.in);
BigDecimal s1 = read.nextBigDecimal();
BigDecimal s2 = read.nextBigDecimal();
System.out.println(s1.divide(s2, 12, BigDecimal.ROUND_HALF_UP).doubleValue());
【9】取相反数:使用negate()函数
Scanner read = new Scanner(System.in);
BigInteger BI = read.nextBigInteger();
BI = BI.negate();
/// BI = -BI; /// 非法!
System.out.println(BI);
学了这么多高精度函数,不是高精度随便A??
核心代码
import java.util.Scanner;
import java.math.*;
public class Main {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int n = read.nextInt();
BigInteger BF[] = new BigInteger[60];
BF[1] = new BigInteger("1");
BigInteger ans = new BigInteger("1");
for(int i = 2;i <= n;++i) {
BigInteger t = new BigInteger("0" + i);
BF[i] = BF[i-1].multiply(t);
ans = ans.add(BF[i]);
}
System.out.println(ans);
}
}