您的位置:首页 > 其它

Codeforces#304-D - Soldier and Number Game-求因子个数/数学

2015-10-14 00:51 323 查看
题意:

给a,b(a>=b)

求a!/b! 的所有因子个数

a范围【1,5000000】,样例1000000组

也就是求 (b+1)(b+2).....a这些数的因子个数之和

显然打表就好了。

打个素数表,过程中顺便把合数的因子个数求一下

最后统计下前缀和就ok

直接输出ans[a]-ans[b]

耗时1559ms

最后面还有一个 1S的代码。

/* 其实打表 可以再优化一点,

看到别人是这样打的

for(i=2;i<5000005;i++)
{
if(a[i])
{
prime[j++]=i;
record[i]=1;
}
else
{
for(int k=0;k<j;k++)
{
if(i%prime[k]==0)
{
record[i]=record[i/prime[k]]+1;
break;
}
}
}
}

ac代码:

#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <algorithm>
#include <iostream>
#include <queue>
#include <deque>
#include <set>
#include <vector>
using namespace std;
const int MAX=5000000;
bool f[MAX+50];
int ans[MAX+50];
int main()
{
int t;
cin>>t;
__int64 i,j;
f[1]=true;

for (i=2;i<=MAX;i++)    //1处
{
if (f[i]==false)           //优化
{
ans[i]=1;
for (j=(__int64)i+i;j<=MAX;j=j+i)   // 如果1处用1000必须_int64强制转换
{
f[j]=true;
int tmp=j;
while(tmp%i==0)
{
ans[j]++;
tmp=tmp/i;
}
}
}
}

ans[2]=1;
for (i=2;i<=MAX;i++)
{
ans[i]+=ans[i-1];
}

while(t--)
{
int a,b;
scanf("%d%d",&a,&b);

printf("%d\n",ans[a]-ans[b]);
}

return 0;

}


优化了一步。。。跑了1S

#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <algorithm>
#include <iostream>
#include <queue>
#include <deque>
#include <set>
#include <vector>
using namespace std;
const int MAX=5000000;
bool f[MAX+50];
int ans[MAX+50];
int main()
{
int t;
cin>>t;
__int64 i,j;
f[1]=true;

for (i=2;i<=MAX;i++)
{
if (f[i]==false)
{
ans[i]=1;
for (j=(__int64)i+i;j<=MAX;j=j+i)
{
f[j]=true;
if (j%i==0)
{
ans[j]=ans[j/i]+1; //递推过来

}
}
}
}
ans[2]=1;
for (i=2;i<=MAX;i++)
{
ans[i]+=ans[i-1];
}
while(t--)
{
int a,b;
scanf("%d%d",&a,&b);

printf("%d\n",ans[a]-ans[b]);
}

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: