题解 | 【模板】分数取模

【模板】分数取模

https://www.nowcoder.com/practice/23839ef20d5f4dbaa9664daa51864291

经典的分数取模,不能直接除,要使用模逆元改为相乘的形式,然后a乘b的模逆元后还要加上模数,因为a可能是负数,这是取余的一个性质,最后还要再取模


import java.math.BigInteger;
import java.util.Scanner;
public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc=new Scanner(System.in);
		int p=1000000007;
		int t=sc.nextInt();
		while(t-->0) {
			BigInteger a=new BigInteger(""+sc.nextInt());
			BigInteger b=new BigInteger(""+sc.nextInt());
			a=(a.multiply(b.modInverse(new BigInteger(""+p)).add(new BigInteger(""+p))).mod(new BigInteger(""+p)));
			System.out.println(a);
		}

	}

}

全部评论

相关推荐

04-24 18:13
南京大学 Java
不吃酸菜血肠:看力竭了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务