Rng(求逆元)

Posted 博学善思

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Rng(求逆元)相关的知识,希望对你有一定的参考价值。

Problem Description
Avin is studying how to synthesize data. Given an integer n, he constructs an interval using the following method: he first generates a integer r between 1 and n (both inclusive) uniform-randomly, and then generates another integer l between 1 and r (both inclusive) uniform-randomly. The interval [l, r] is then constructed. Avin has constructed two intervals using the method above. He asks you what the probability that two intervals intersect is. You should print p* q(1)(MOD 1, 000, 000, 007), while pq denoting the probability.
 

求逆元的几种方法:https://blog.csdn.net/xiaoming_p/article/details/79644386

Input
Just one line contains the number n (1 ≤ n ≤ 1, 000, 000).
 

 

Output
Print the answer.
 

 

Sample Input
1
2
 

 

Sample Output
1
750000006
 
规律:(n+1)*n/2/(n*n)
代码:
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
#include<stack>
#include<set>
#include<vector>
#include<map>
#include<cmath>
const int maxn=1e5+5;
const long long  mod=1e9+7; 
typedef long long ll;
using namespace std;

ll ksm(ll x,ll y)
{
  ll ans=1;
  while(y)
  {
      if(y&1)
      ans=ans*x%mod;
      y>>=1;
      x=x*x%mod;
  }
  return ans;
} 
int main()
{
   ll n;
   while(cin>>n)
   {
       ll p=(n+1)*n/2;
       ll q=n*n;
       printf("%lld\n",(p*ksm(q,mod-2))%mod);
   } 
   return 0;
}

 

 
 

以上是关于Rng(求逆元)的主要内容,如果未能解决你的问题,请参考以下文章

求逆元的四大基本方法

线性求逆元

求逆元

AcWing 876. 快速幂求逆元

数论——快速幂,模运算及快速幂求逆元

求逆元的常用方法