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.
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
Source
题解:
题意:
给你一段区间1-n,可以从这个这个区间里找到一个点,记为r,从1-r找到一个点,记为l,问通过这个方法找任意两个区间的概率。
解答:
求算相交的概率,就是求算1减去不相交的概率,因为相交的概率并不好求,所以可以先转化一下角度。
根据古典概型理论,全部的情况为n*n
不相交的所有情况就是左区间的右端点小于右区间的左端点的所有位置,即等差数列n*(n-1)/2;
所以所求概率为1 - ((n*(n-1)) / 2 / n*n);
题目要求答案是p/q(mod 1e9+7)
因为运算要进行取模,所以除法要变成乘以其逆元,求逆元可以用费马小定理,a的逆元为a^(mod-2).
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <cstdio>
using namespace std;
typedef long long ll;
const ll mod=1e9+7;
ll ksm(ll a,ll n)
{
ll res=1;
while(n)
{
if(n&1) res=res*a%mod;
a=a*a%mod;
n>>=1;
}
return res;
}
int main()
{
ll n;
while(cin>>n)
{
cout<<(n+1)*ksm(n*2,mod-2)%mod<<endl;
}
return 0;
}