Hackerrank Random Number Generator

https://www.hackerrank.com/challenges/random-number-generator-1

Pi>=0$P_i>=0$
1=Σni=1Pi$1=Σ_{i=1}^{n}P_i$

f(x)=Σni=1Pi(1Pi)i$f(x)=Σ_{i=1}^{n}P_i*(1-Pi)*i$
φ(x)=Σni=1Pi1$φ(x)=Σ_{i=1}^{n}P_i -1$
F(x,φ)=Σni=1Pi(1Pi)iλ(Σni=1Pi1)$F(x,φ)=Σ_{i=1}^{n}P_i*(1-Pi)*i-λ(Σ_{i=1}^{n}P_i -1)$

F(x,φ)xi=i2Piiλ=0$F'(x,φ)_{xi}=i-2P_i*i-λ=0$
iλ=2Pii$i-λ=2P_i*i$
Pi=0.5λ/(2i)$P_i=0.5-λ/(2*i)$

Pi=0.5λ/(2i)$P_i=0.5-λ/(2*i)$
Σni=1Pin0.5λ0.5(Σni=11/n)=1$Σ_{i=1}^{n}P_in*0.5-λ*0.5*(Σ_{i=1}^n 1/n)=1$
λ=(n2)/(Σni=11/n)$λ=(n-2)/(Σ_{i=1}^n 1/n)$
λn/ln(n)$λ≈n/ln(n)$

#include<cstdio>
#include<cstring>
using namespace std;

double f[1000001];

int main()
{
int n;
n=1000000;
int i;
for(int i=1;i<=n;i++)f[i]=f[i-1]+1.0/i;
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
if(n==1){puts("0.00000000000");continue;}
if(n==2){puts("0.50000000000");continue;}
int l=1,mid,r=n;
while(l<r)
{
mid=l+r>>1;
double F=(n-mid-1)/(f[n]-f[mid-1]);
if(0.5-F/2/mid>=0)r=mid;
else l=mid+1;
}
r=n;
double F=(r-l-1)/(f[r]-f[l-1]);
double As=(r-l+1)*1ll*(r+l)/4.0-F*F/2*(f[r]-f[l-1]);
printf("%.10f\n",As/(2*n-1));
}
return 0;
}