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;
}

 

 
 
posted @ 2019-07-21 15:41  black_hole6  阅读(457)  评论(2编辑  收藏  举报