f(n) = (1+n)*n/2
此為等差公式
g(n) = f(n) + g(n-1)
移項
g(n) - g(n-1) = f(n)
g(n) - g(n-1) = 1/2 n^2 + 1/2 n
g(n-1) - g(n-2) = 1/2 (n-1)^2 + 1/2 (n-1)
........
g(2) - g(1) = 1/2 (2)^2 + 1/2 (2)
全部加起來
=> g(n) - g(1) = (1/2 )( 2^2 + 3^2 + ... + n^2) + (1/2 )( 2 + 3 + ...+ n)
g(n) = (1/2 )(1^2 +2^2 + 3^2 + ... + n^2) + (1/2 )(1 + 2 +3 +... + n)
= (1/2 )( n*(n+1)*(2n+1) / 6) + (1/2 )f(n)
= f(n)(2n+1) / 6 + (1/2 )f(n)
= f(n)*(n + 2) / 3;
#include <iostream>
using namespace std;
int main()
{
int n;
unsigned long long int f, g;
while(cin >> n)
{
f = (1+n)*n/2;
g = f*(n+2)/3;
cout << f << " " << g << endl;
}
return 0;
}
留言列表