数论筛法(不定期更新)

题目一: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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值