数学问题 Hdu 2802 F(n)

来源:互联网 发布:搞笑照片贴图软件 编辑:程序博客网 时间:2024/06/09 23:31

F(N)

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1651 Accepted Submission(s): 542


Problem Description
hdu 2802 - fudq - fudq的博客
Giving the N, can you tell me the answer of F(N)?

Input
Each test case contains a single integer N(1<=N<=10^9). The input is terminated by a set starting with N = 0. This set should not be processed.

Output
For each test case, output on a line the value of the F(N)%2009.

Sample Input
1 2 3 0

Sample Output
1 7 20
————————————————————————————————————
从题中可看出,有循环体,所以一种解法直接找出循环体即可;
另一种解法,推出公式求解:
1.N为偶数
最后一项f(4)-f(2)=4^3-3^3
所有式子相加得
f(N)= 2^3+4^3+....+N^3 
-1^3-3^3-....-(N-1)^3
通项 N^3-(N-1)^3
N=2,4,6.......N   
设N=2*n
通项 12*n^2-6*n+1
平方和公式n(n+1)(2n+1)/6 
f(n)= sum(12*n^2-6*n+1) (n=1,2,3...,N/2)
= 4*n^3+3*n^2
f(N)=N^3/2+3*N^2/4

2.N为奇数
最后一项f(3)-f(1)=3^3-2^3
f(N)= 1^3+3^3+....+N^3 
-0^3-2^3-....-(N-1)^3
通项 N^3-(N-1)^3
N=1,3,5.......N 
设N=2*n-1
通项 12*n^2-18*n+7
f(n)= sum(12*n^2-18*n+7) (n=1,2,3...,(N+1)/2)
= 4*n^3-3*n^2
f(N)=((N+1)/2)^2*(2*N-1)
————————————————————————————————————
AC Code:
#include <iostream>
using namespace std;

int f[5000];
int main()
{
int
 i,n;
f[1]=1;
f[2]=7;
f[3]=20;
i=4;
while (1
)
{
f[i]=(f[i-2]+3*i*i-3*i+1)%2009;
if (f[i-2]==1&&f[i-1]==7)
break
;
i
++;
}

while (scanf("%d",&n)!=EOF
)
{
if (n==0)
return
 0;
n%=4018;
printf("%d\n",f[n
]);
}
return 0
;
}
 
 
利用公式:
#include <iostream>
using namespace std;

int main()
{
__int64 f[5000],i,n;
f[1]=1;
f[2]=7;
f[3]=20;
for (i=4;i<=4300;i++)
{
if (i%2==0)
{
f[i]=(i*i*i/2+3*i*i/4)%2009;
}
else
{
f[i]=((i+1)/2)*((i+1)/2)*(2*i-1)%2009;
}
}
while (scanf("%I64d",&n)!=EOF)
{
if (n==0)
return 0;
n%=4018;
printf("%I64d\n",f[n]);
}
return 0;
}
0 0