hdu 2139 Calculate the formula

纯数学题,推理如下:

已知:1^2+2^2+3^2+……+n^2 =n(n+1)(2n+1)/6 —①
那么1^2+2^2+3^2+……+n^2+……+(2n+1)^2 =(2n+1)(n+1)(4n+3)/3 —②
又有2^2+4^2+6^2+……+(2n)^2 =4[1^2+2^2+3^2+……+n^2]=4*①=2n(n+1)(2n+1)/3 —③
设所求为S 比较②和③可知 S=②-③=(2n+1)(n+1)(4n+3)/3-2n(n+1)(2n+1)/3
=(2n+1)(n+1)(2n+3)/3 —④
因为S是2n+1项的和 把它一般化 则奇数项平方和一般公式Sn=n(n+1)(n+2)/6

注意要用long long保证不溢出!

#include<iostream>
#include<vector>
#include<map>
#include<stack>
#include<algorithm>
#include<queue>
#include<list>
#include<set>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<stdio.h>
#include<ctype.h>
#include<iomanip>
using namespace std;

#define LL long long

int main()
{
    LL n;
    while(scanf("%I64d",&n)!=EOF)
    {
        LL ans=n*(n+1)*(n+2)/6;
        printf("%I64d\n",ans);
    }
    return 0;
}


 

你可能感兴趣的:(hdu 2139 Calculate the formula)