题目一:Help Hanzo LightOJ - 1197 素数区间筛
分析:
可以通过[2, sqrt(b)]的素数将[a, b]的合数筛出来,剩余的就是素数
最后判断一下a=1的情况
代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
//typedef __int128 lll;
#define print(i) cout << "debug: " << i << endl
#define close() ios::sync_with_stdio(0), cin.tie(0), cout.tie(0)
#define mem(a, b) memset(a, b, sizeof(a))
const ll mod = 1e9 + 7;
const int maxn = 1e5 + 10;
const int inf = 0x3f3f3f3f;
int vis[maxn];
int p[maxn], tot;
int v[maxn];
void make()
{
for(int i = 0; i < maxn; i++) vis[i] = 1;
for(int i = 2; i < maxn; i++)
if(vis[i])
{
p[tot++] = i;
for(int j = i * 2; j < maxn; j += i)
vis[j] = 0;
}
}
ll calc(ll a, ll b)
{
for(int i = 0; i < b - a + 1; i++) v[i] = 1;
for(int i = 0; i < tot && p[i] <= (int)sqrt(b); i++)
{
ll j;
if(p[i] >= a) j = 2 * p[i];
else if(a % p[i]) j = a - a % p[i] + p[i];
else j = a;
for( ; j <= b; j += p[i])
v[j - a] = 0;
}
int res = 0;
for(int i = 0; i < b - a + 1; i++)
if(v[i])
res++;
if(a == 1) res--;
return res;
}
int main()
{
int t, cases = 0; cin >> t;
ll a, b;
make();
while(t--)
{
cin >> a >> b;
printf("Case %d: %lld\n", ++cases, calc(a, b));
}
}
题目二:GCD - Extreme (II) UVA - 11426 欧拉筛
分析:
顺瓜摸藤:可以枚举gcd,对于当前枚举的gcd,再枚举他的所有倍数n,此时我们想知道有几个x,使得gcd(n,x) = gcd,phi[n/gcd]其实就是答案。因为并不是x的任意两个倍数的最大公因数都是gcd,比如gcd=2,n = 8,x = 4,此时gcd(n, x)就是4而不是2.因此我们需要保证n和x除以gcd之后能够互质,这里需要欧拉打表。
代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
//typedef __int128 lll;
#define print(i) cout << "debug: " << i << endl
#define close() ios::sync_with_stdio(0), cin.tie(0), cout.tie(0)
#define mem(a, b) memset(a, b, sizeof(a))
const ll mod = 1e9 + 7;
const int maxn = 4e6 + 10;
const int inf = 0x3f3f3f3f;
ll phi[maxn];
ll a[maxn], sum[maxn];
void make()
{
phi[1] = 1;
for(int i = 2; i < maxn; i++)
if(!phi[i])
{
for(int j = i; j < maxn; j += i)
{
if(!phi[j]) phi[j] = j;
phi[j] = phi[j] / i * (i - 1);
}
}
for(int i = 1; i < maxn; i++)
for(int j = i * 2; j < maxn; j += i)
a[j] += phi[j / i] * i;
for(int i = 2; i < maxn; i++)
sum[i] = sum[i - 1] + a[i];
}
int main()
{
ll n;
make();
while(cin >> n && n)
{
cout << sum[n] << endl;
}
}