试题B:相乘
题目
题目重点
- (数字*2021)会超出int的最大范围,算是一个隐藏的坑,如果没有注意到这个,就会得出0的结果。
- 这里要用到BigInteger大数字、String.valueOf()将int转换为字符串
- multiply乘、mod取余
代码
import java.math.BigInteger;
public class Main {
public static void main(String[] args) {
//(i*2021)%1000000007 == 999999999
BigInteger num999999999 = new BigInteger("999999999");
BigInteger num2021 = new BigInteger("2021");
BigInteger num1000000007 = new BigInteger("1000000007");
for (int i = 0; i < 1000000007; i++) {
BigInteger a = new BigInteger(String.valueOf(i));//i转换成大数
BigInteger mul = a.multiply(num2021);
BigInteger mod = mul.mod(num1000000007);
if(mod.equals(num999999999)) {
System.out.println(i);
break;
}
}
}
}
答案
17812964