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