hdu2132

题目:We once did a lot of recursional problem . I think some of them is easy for you and some if hard for you.
Now there is a very easy problem . I think you can AC it.
  We can define sum(n) as follow:
  if i can be divided exactly by 3 sum(i) = sum(i-1) + i*i*i;else sum(i) = sum(i-1) + i;
  Is it very easy ? Please begin to program to AC it..-_-

output the result sum(n).

1 2 3 -1
1 3 30
题解:对于这道题我有两种解法:1、题目已经给出1 2 3的sum[i],对于公式sum(i) = sum(i-1) + i*i*i,只要知道知道前一个数,就可以算出后一个数,就可以用一个for循环,算出后面的数,存成一个数组,在知道i值后,直接在数组里面调出就可以了。不过这个数组要给的很大。2、用函数来做,用递归思想,也涉及到循环,不过不用开数组。
#include<stdio.h>
int main()
{
    __int64 a[100006];
    __int64 n,i;
    a[0]=0;
    a[1]=1;
    a[2]=3;
    for(i=3;i<=100000;i++)
    {
        if(i%3==0) a[i]=a[i-1]+i*i*i;
        else a[i]=a[i-1]+i;
    }
    while(scanf("%I64d",&n)!=EOF)
    {
        if(n<0) break;
        printf("%I64d\n",a[n]);
    }

    return 0;
}

猜你喜欢

转载自www.cnblogs.com/qiuhua7777/p/9163767.html