Rewrite the sum in the form:
The sum in parentheses is 2^n. If in Newton’s binomial formula
we set a = b = 1, then we get the relation: (1 + 1)^n = \sum_{i=0}^n{C_n^i1^i1^{n-i}}, or
Let’s compute the remaining sum:
So the answer is 2^n + n \cdot 2^{n - 1} = (n + 2) \cdot 2^{n - 1}.
Example
Compute the value for n = 3. For direct calculation:
When calculated using the formula: 5 \cdot 2^2 = 20.
Algorithm implementation
Read the input value of .
scanf("%lld", &n);Compute and print the answer.
res = (1LL << (n - 1)) * (n + 2);
printf("%lld\n", res);Algorithm implementation — function
Declare an array to store the results: dp[n][k] = C_n^k.
int dp[31][31];The Cnk function computes the value of the binomial coefficient C_n^k.
int Cnk(int n, int k)
{
if (n == k) return 1;
if (k == 0) return 1;
if (dp[n][k] != -1) return dp[n][k];
return dp[n][k] = (Cnk(n - 1, k - 1) + Cnk(n - 1, k)) % 9929;
}The main part of the program. Read the input value of .
scanf("%d", &n);
memset(dp, -1, sizeof(dp));Compute the required sum.
res = 0;
for (i = 0; i <= n; i++)
res += (i + 1) * Cnk(n, i);Print the answer.
printf("%d\n", res);Python implementation — comb function
import mathRead the input value of .
n = int(input())Compute the required sum. To compute the binomial coefficient, we’ll use the built-in function comb.
res = 0
for i in range(n + 1):
res += (i + 1) * math.comb(n, i)Print the answer.
print(res)Python implementation — function
The Cnk function computes the value of the binomial coefficient C_n^k.
def Cnk(n, k, dp):
if n == k: return 1
if k == 0: return 1
if dp[n][k] != -1: return dp[n][k]
dp[n][k] = Cnk(n - 1, k - 1, dp) + Cnk(n - 1, k, dp)
return dp[n][k]The main part of the program. Read the input value of .
n = int(input())Initialize all the elements of the two-dimensional list dp with the value . We shall use this list to memoize the results: dp[n][k] = C_n^k.
dp = [[-1 for _ in range(31)] for _ in range(31)]Compute the required sum.
res = 0
for i in range(n + 1):
res += (i + 1) * Cnk(n, i, dp)Print the answer.
print(res)Python implementation — formula
Read the input value of .
n = int(input())Compute the answer using the formula.
res = (1 << (n - 1)) * (n + 2)Print the answer.
print(res)