Rng (规律+逆元+概率)

Rng

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)q(−1)(MOD 1, 000, 000, 007), while pqpq 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

这道题的意思是在1到n的区间中找出两个序列,求两个序列不相交的概率,我们可以求出他相交的概率。

首先在1到n的区间中选择第一个序列的右端,其选择的概率为1/n,标记为i,然后选择左端,选择的概率为1/i。

最后的概率公式为n+1/2*n(我并求不粗来。。)其逆元用费马小定理为a^(p-1)=1(mod p) 即a^(p-2)=a^-1(mod p)

#include
 
using namespace std;
long long mod=1000000007;
long long qpow(long long a,long long b){
	if(b<0) return 0;
	long long res=1;
	a%=mod;
	while(b){
		if(b&1){
			res*=a;
			res%=mod;
		}
		b>>=1;
		a*=a;
		a%=mod;
	}
	return res;
}

int main(){
	ios::sync_with_stdio(0);
	cin.tie(0),cout.tie(0);
	long long n;
	while(cin>>n){
		long long ans=((n+1)*qpow(2*n,mod-2))%mod;
		cout<

 

 

 

你可能感兴趣的:(算法)