HDU 2824 The Euler function --------欧拉模板

时间:2023-03-09 19:24:32
HDU 2824  The Euler function --------欧拉模板

The Euler function

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

Problem Description
The Euler function phi is an important kind of function in number theory, (n) represents the amount of the numbers which are smaller than n and coprime to n, and this function has a lot of beautiful characteristics. Here comes a very easy question: suppose you are given a, b, try to calculate (a)+ (a+1)+....+ (b)
Input
There are several test cases. Each line has two integers a, b (2<a<b<3000000).
Output
Output the result of (a)+ (a+1)+....+ (b)
Sample Input
3 100
Sample Output
3042
第一种打表的方法是,素数和欧拉,分开来打表。250ms
第二种打表只有一个,但是时间上更多。500ms
 #include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
using namespace std; int prime[],len;
int opl[];
bool s[]; void Getprime() //打素数表
{
int i,j;
len=;
for(i=;i<=;i++)
{
if(s[i]==false)
{
prime[++len]=i;
for(j=i*;j<=;j=j+i)
s[j]=true;
}
}
} void Euler() //欧拉打表。
{
int i,j;
Getprime();
for(i=;i<=;i++)
opl[i]=i;
opl[]=;
for(i=;i<=len;i++)
{
for(j=prime[i];j<=;j=j+prime[i])
opl[j]=opl[j]/prime[i]*(prime[i]-); //利用的定理 }
} int main()
{
int n,m,i;
__int64 num;
Euler();
while(scanf("%d%d",&n,&m)>)
{
num=;
for(i=n;i<=m;i++)
num=num+opl[i];
printf("%I64d\n",num);
}
return ;
}

第二种方法。

 #include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
using namespace std; int opl[];
bool s[]; void Euler() //欧拉打表。
{
int i,j;
for(i=;i<=;i++)
opl[i]=i;
opl[]=; for(i=;i<=;i++)
if(s[i]==false)
{
for(j=i;j<=;j=j+i)
{
opl[j]=opl[j]/i*(i-);
s[j]=true;
}
}
} int main()
{
int n,m,i;
__int64 num;
Euler();
while(scanf("%d%d",&n,&m)>)
{
num=;
for(i=n;i<=m;i++)
num=num+opl[i];
printf("%I64d\n",num);
}
return ;
}