首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

关于结成求和的时间复杂度,该如何处理

2012-05-16 
关于结成求和的时间复杂度题目描述The GNU Compiler Collection (usually shortened to GCC) is a compile

关于结成求和的时间复杂度
题目描述
The GNU Compiler Collection (usually shortened to GCC) is a compiler system produced by the GNU Project supporting various programming languages. But it doesn’t contains the math operator “!”.

In mathematics the symbol represents the factorial operation. The expression n! means "the product of the integers from 1 to n". For example, 4! (read four factorial) is 4 × 3 × 2 × 1 = 24. (0! is defined as 1, which is a neutral element in multiplication, not multiplied by anything.)

We want you to help us with this formation: (0! + 1! + 2! + 3! + 4! + ... + n!)%m.

输入
The first line consists of an integer T, indicating the number of test cases.

Each test on a single consists of two integer n and m.

0 < T <= 20
0 <= n < 10100 (without leading zero)
0 < m < 1000000

输出
Output the answer of (0! + 1! + 2! + 3! + 4! + ... + n!)%m.


示例输入
1
10 861017
示例输出
593846
下面是我的答案:


#include<stdio.h>
long int fac(int n);

void main()
{
int T,i,j;
long a[20]={0};
long int n,m;
scanf("%d",&T);
for(i=1;i<=T;i++)
{
scanf("%ld%ld",&n,&m);
for(j=0;j<=n;j++)
{
a[i-1]+=fac(j);
a[i-1]=a[i-1]%m;
}


}
for(i=0;i<T;i++)
printf("%ld\n",a[i]);




}

long int fac(int n)
{
long f;
if(n==1||n==0)
f=1;
else
f=n*fac(n-1);
return (f);




我这个程序的运行时间是1010ms,但要求运行时间必须在1000Ms内。求高手指点修改,谢谢


[解决办法]
#include<stdio.h>
void main()
{
int T,i,j;
int a;
int n,m,temp;
scanf("%d",&T);
for(i=1;i<=T;i++)
{
scanf("%d%d",&n,&m);
a=1;
temp=1;
for(j=1;j<=n;j++)
{
temp=(j*temp)%m;
a+=temp;
a=a%m;
if(temp==0)
break;
}
printf("%d\n",a);
}
}
[解决办法]
直接算fac肯定溢出答案错误。

C/C++ code
int result, t;result = t = 1%m;for(int i=1;i<=n;i++){  t = t*i%m;  result = (result+t)%m;} 

热点排行