# CFR 622 F. The Sum of the k-th Powers ( Lagrange's Interpolation, Math )

Problem - 622F - Codeforces

1 ≤ N ≤ 1e9
0 ≤ K ≤ 1e6

O( K lg MOD )

#include <bits/stdc++.h>
using namespace std;

const int MAXN = int( 1e9 );
const int MAXK = int( 1e6 );
const int MOD = int( 1e9 ) + 7;

int int_pow( int v, int p ) {
int res = not ( v == 0 and p );
while( p ) {
if( p & 1 ) {
res = 1LL * res * v % MOD;
}
p >>= 1;
v = 1LL * v * v % MOD;
}
return res;
}

int inv( int v ) {
return int_pow( v, MOD - 2 );
}

int fact[ MAXK + 1 + 1 ];

int N, K;

int f[ MAXK + 2 + 1 ];

signed main() {
ios::sync_with_stdio( 0 );
cin >> N >> K;
for( int i = fact[ 0 ] = 1; i <= K + 1; ++i ) {
fact[ i ] = 1LL * fact[ i - 1 ] * i % MOD;
}
for( int i = 1; i <= K + 2; ++i ) {
f[ i ] = ( f[ i - 1 ] + int_pow( i, K ) ) % MOD;
}
if( N <= K + 2 ) {
cout << f[ N ] << endl;
exit( 0 );
}
int xmj = 1;
for( int i = 1; i <= K + 2; ++i ) {
xmj = 1LL * xmj * ( N - i ) % MOD;
}
int ans = 0;
for( int i = 1; i <= K + 2; ++i ) {
int p = 1LL * f[ i ] * xmj % MOD * inv( N - i ) % MOD * inv( 1LL * fact[ i - 1 ] * fact[ K + 2 - i ] % MOD ) % MOD;
if( K + 2 - i & 1 ) p *= -1;
( ans += p ) %= MOD;
}
if( ans < 0 ) ans += MOD;
cout << ans << endl;
return 0;
}