在比赛时,由于c++没有大数类型,需要自己模拟大数等操作,给程序编写带来不便,所以在不考虑时间的情况下,用JAVA做大数题目是首选,当然可以使用python当我没说。
介绍两个JAVA主要的类:java.math.BigInteger和java.math.BigDecimal
BigInteger
1:创建,读入,输出
public class Demo6 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
BigInteger a = new BigInteger("0"); //创建一个值为0的大数
BigInteger b = scanner.nextBigInteger(); //读入一个大数
System.out.println(b); //输出b
}
}
2:比较运算
public class Demo6 {
public static void main(String[] args) {
BigInteger a = new BigInteger("2");
BigInteger b = new BigInteger("3");
if(a.compareTo(b) > 0) { //比较a是否大于b
System.out.println("a > b");
} else if(a.compareTo(b) == 0) { //比较a是否等于b
System.out.println("a = b");
} else if(a.compareTo(b) < 0) { //比较a是否小于b
System.out.println("a < b");
}
}
}
3:加减乘除
public class Demo6 {
public static void main(String[] args) {
BigInteger a = new BigInteger("12");
BigInteger b = new BigInteger("5");
System.out.println(a.add(b)); // 加操作 17
System.out.println(a.subtract(b)); //减操作 a - b 7
System.out.println(a.multiply(b)); //乘操作 60
System.out.println(a.divide(b));
//除操作 a / b 2 这里的除操作是a / b向下取整后的结果
}
}
4:最大公约数 最小公倍数
public class Demo6 {
public static void main(String[] args) {
BigInteger a = new BigInteger("12");
BigInteger b = new BigInteger("5");
System.out.println(a.gcd(b)); //a和b的最大公约数
BigInteger LCM = a.multiply(b).divide(a.gcd(b)); //a和b的最小公倍数
System.out.println(LCM);
}
}
5:逆元
public class Demo6 {
public static void main(String[] args) {
BigInteger a = new BigInteger("12");
System.out.println(a.modInverse(new BigInteger("1000000007"))); // a 在1e9 + 7下的逆元
}
}
6:快速幂
public class Demo6 {
public static void main(String[] args) {
BigInteger a = new BigInteger("2");
BigInteger b = new BigInteger("5");
System.out.println(a.modPow(b, new BigInteger("31"))); //计算a的b次方mod 31后的结果
//内部实现是快速幂
}
}
7:左移 右移
public class Demo6 {
public static void main(String[] args) {
BigInteger a = new BigInteger("2");
System.out.println(a.shiftLeft(2)); //左移2位
System.out.println(a.shiftRight(2)); //右移2位
}
}
8:或 与 异或
public class Demo6 {
public static void main(String[] args) {
BigInteger a = new BigInteger("7");
BigInteger b = new BigInteger("1");
System.out.println(a.or(b)); //或
System.out.println(a.xor(b)); //异或
System.out.println(a.and(b)); //与
}
}
还有一些其他函数就不一一列举了
BigDecimal和BigInteger方法基本类似,就不说了,会一个另一个就会了