All Euler problems
Project Euler

Hypergeometric Sums

Evaluate S = sum_(k=0)^1000 C(2000, k)^2 mod 10^9+7.

Source sync Apr 19, 2026
Problem #0946
Level Level 31
Solved By 269
Languages C++, Python
Answer 585787007
Length 98 words
modular_arithmeticbrute_forcecombinatorics

Problem Statement

This archive keeps the full statement, math, and original media on the page.

Given the representation of a continued fraction

is a real number with continued fraction representation:
where the number of 's between each of the 's are consecutive prime numbers.

is another real number defined as

The first ten coefficients of the continued fraction of are with sum .

Find the sum of the first coefficients of the continued fraction of .

Problem 946: Hypergeometric Sums

Mathematical Analysis

Vandermonde-Chu Identity

Theorem. k=0n(nk)2=(2nn)\sum_{k=0}^{n} \binom{n}{k}^2 = \binom{2n}{n}.

However, our sum is truncated at k=1000<2000k = 1000 < 2000. By symmetry (2000k)=(20002000k)\binom{2000}{k} = \binom{2000}{2000-k}, and we are summing the first 1001 terms of a 2001-term sum.

k=02000(2000k)2=(40002000)\sum_{k=0}^{2000} \binom{2000}{k}^2 = \binom{4000}{2000}.

By symmetry: (2000k)2=(20002000k)2\binom{2000}{k}^2 = \binom{2000}{2000-k}^2, so the sum splits evenly except for the middle term:

k=01000(2000k)2=12((40002000)+(20001000)2)\sum_{k=0}^{1000} \binom{2000}{k}^2 = \frac{1}{2}\left(\binom{4000}{2000} + \binom{2000}{1000}^2\right)

Modular Computation

Compute (40002000)modp\binom{4000}{2000} \bmod p and (20001000)2modp\binom{2000}{1000}^2 \bmod p using precomputed factorials and modular inverses.

Concrete Steps

  1. Precompute n!modpn! \bmod p for n4000n \leq 4000.
  2. Compute modular inverses via n!1(n!)p2(modp)n!^{-1} \equiv (n!)^{p-2} \pmod{p}.
  3. Apply the symmetry formula.

Proof of Correctness

  1. Vandermonde identity: (nk)2=(2nn)\sum \binom{n}{k}^2 = \binom{2n}{n}.
  2. Symmetry: (nk)2=(nnk)2\binom{n}{k}^2 = \binom{n}{n-k}^2.
  3. Half-sum formula: Exact when nn is even and we sum to n/2n/2.

Complexity Analysis

  • Factorial precomputation: O(N)O(N).
  • Final computation: O(logp)O(\log p) for modular inverse.

Answer

585787007\boxed{585787007}

Code

Each problem page includes the exact C++ and Python source files from the local archive.

C++ project_euler/problem_946/solution.cpp
#include <bits/stdc++.h>
using namespace std;
const long long MOD=1e9+7;
long long pw(long long a,long long b,long long m){long long r=1;a%=m;while(b>0){if(b&1)r=r*a%m;a=a*a%m;b>>=1;}return r;}
int main(){
    int N=4001;
    vector<long long> f(N),fi(N);
    f[0]=1;for(int i=1;i<N;i++) f[i]=f[i-1]*i%MOD;
    fi[N-1]=pw(f[N-1],MOD-2,MOD);
    for(int i=N-2;i>=0;i--) fi[i]=fi[i+1]*(i+1)%MOD;
    auto C=[&](int n,int k)->long long{
        if(k<0||k>n) return 0;
        return f[n]%MOD*fi[k]%MOD*fi[n-k]%MOD;
    };
    long long a=C(4000,2000), b=C(2000,1000);
    long long ans=(a+b%MOD*b%MOD)%MOD*pw(2,MOD-2,MOD)%MOD;
    cout<<ans<<endl;
}