Bubble Cup 13 - Finals [Online Mirror, unrated, Div. 1]K. Lonely Numbers【打表+线性筛模板+前缀和】

本文针对一组数字中的“孤独数字”进行定义与求解,通过筛选素数并利用前缀和技巧,快速找出指定范围内所有孤独数字的数量。适用于算法竞赛及数学问题解决。

题目

传送门
In number world, two different numbers are friends if they have a lot in common, but also each one has unique perks.

More precisely, two different numbers a and b are friends if gcd(a,b), agcd(a,b), bgcd(a,b) can form sides of a triangle.

Three numbers a, b and c can form sides of a triangle if a+b>c, b+c>a and c+a>b.

In a group of numbers, a number is lonely if it doesn’t have any friends in that group.

Given a group of numbers containing all numbers from 1,2,3,…,n, how many numbers in that group are lonely?

Input
The first line contains a single integer t (1≤t≤106) - number of test cases.

On next line there are t numbers, ni (1≤ni≤106) - meaning that in case i you should solve for numbers 1,2,3,…,ni.

Output
For each test case, print the answer on separate lines: number of lonely numbers in group 1,2,3,…,ni.

输入
3
1 5 10
输出
1
3
3

题意:t个数,下面是n1~nt,对于每个ni我们要求出1—ni共有多少个孤独数字,孤独数字的定义为1-n中,某个数字a对任意的数字b都不满足gcd(a,b), a/gcd(a,b), b/gcd(a,b)可以构成三角形;

思路:暴力打表之后我们可以发现孤独数字都是素数,但是有的素数不是孤独数字当且仅当他的平方出现在1-ni中,所以n的范围是1e6,我们可以先筛出范围内的所有数字再用前缀和打表求解,具体看代码;

AC code

#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<sstream>
#include<queue>
#include<stack>
using namespace std;
int ans[1200000],prim[1200000],num[1200000],pn=0;
int n;
void table()
{
    memset(num,-1,sizeof(num));
    for(int i=2;i<1000010;i++)
       {if(num[i])prim[pn++]=i;
       for(int j=0;j<pn&&i*prim[j]<1000010;j++)
         {num[i*prim[j]]=0;
         if(i%prim[j]==0)break;}
       }//线性筛模板
       for(int i=0;i<pn;i++)
     {
         if(prim[i]<=1000)ans[prim[i]*prim[i]]--;//如果素数的平方出现,那么就要减去这个素数,此时这个素数将不再是孤独数字
            ans[prim[i]]++;
     }
     ans[1]=1;
     for(int i=2;i<1000001;i++)ans[i]+=ans[i-1];//前缀和
}
void solve()
{
     printf("%d\n",ans[n]);
}
int main()
{
    ios::sync_with_stdio(0);
    table();
    int t;
    cin>>t;
    while(t--)
    {
     cin>>n;
    solve();}
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值