Problem:
Score : 1800 points

Problem Statement

We have a round pizza. Snuke wants to eat one third of it, or something as close as possible to that.

He decides to cut this pizza as follows.

First, he divides the pizza into N pieces by making N cuts with a knife. The knife can make a cut along the segment connecting the center of the pizza and some point on the circumference of the pizza. However, he is very poor at handling knives, so the cuts are made at uniformly random angles, independent from each other.

Then, he chooses one or more consecutive pieces so that the total is as close as possible to one third of the pizza, and eat them. (Let the total be x of the pizza. He chooses consecutive pieces so that |x - 1/3| is minimized.)

Find the expected value of |x - 1/3|. It can be shown that this value is rational, and we ask you to print it modulo 10^9 + 7, as described in Notes.

Notes

When you print a rational number, first write it as a fraction \frac{y}{x}, where x, y are integers and x is not divisible by 10^9 + 7
(under the constraints of the problem, such representation is always possible).
Then, you need to print the only integer z between 0 and 10^9 + 6, inclusive, that satisfies xz \equiv y \pmod{10^9 + 7}.

Constraints

2 \leq N \leq 10^6

Input

Input is given from Standard Input in the following format:

N

Output

Print the expected value of |x - 1/3| modulo 10^9 + 7, as described in Notes.

Sample Input 1

2

Sample Output 1

138888890

The expected value is \frac{5}{36}.

Sample Input 2

3

Sample Output 2

179012347

The expected value is \frac{11}{162}.

Sample Input 3

10

Sample Output 3

954859137

Sample Input 4

1000000

Sample Output 4

44679646

Solution in C++14 (GCC 5.4.1) (judge verdict: Accepted)

#include<bits/stdc++.h>
using namespace std;
const int N=1e6+5,mod=1e9+7;
int n,ans,a[N],b[N],f[2][N];
int C(int n,int m)
{
    if (m<0||m>n) return 0;
    return 1ll*a[n]*b[m]%mod*b[n-m]%mod;
}
int fpow(int a,int b)
{
    int ans=1;
    while (b)
    {
        if (b&1) ans=1ll*ans*a%mod;
        a=1ll*a*a%mod,b>>=1;
    }
    return ans;
}
int main()
{
    scanf("%d",&n),a[0]=a[1]=b[0]=b[1]=f[0][0]=1;
    for (int i=2;i<=n;i++) a[i]=1ll*i*a[i-1]%mod,b[i]=1ll*(mod-mod/i)*b[mod%i]%mod;
    for (int i=2;i<=n;i++) b[i]=1ll*b[i]*b[i-1]%mod;
    for (int i=1;i<=n;i++) f[0][i]=(f[1][i-1]<<1)%mod,f[1][i]=(f[0][i-1]+f[1][i-1])%mod,ans=(ans+1ll*f[1][i]*C(n,i)%mod*b[i]%mod*a[i-1])%mod;
    printf("%d",1ll*ans*fpow(1ll*fpow(3,n)*n%mod,mod-2)%mod);
    return 0;
}