UVA 10539 Almost Prime Numbers( 素数因子)

本文介绍了一种算法,用于找出特定范围内的几乎质数数量。几乎质数是指仅能被一个质数整除的非质数。文章提供了完整的C++代码实现,并通过样例输入输出展示了如何运行该程序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Almost prime numbers are the non-prime numbers which are divisible by only a single prime number. In this problem your job is to write a program which finds out the number of almost prime numbers within a certain range.

Input
First line of the input file contains an integer N (N <= 600) which indicates how many sets of inputs are there. Each of the next N lines make a single set of input. Each set contains two integer numbers low and high (0 < low <= high < 1012).

Output
For each line of input except the first line you should produce one line of output. This line contains a single integer, which indicates how many almost prime numbers are within the range (inclusive) low…high.

Sample InputSample Output
3
1 10
1 20
1 5
3
4
1

代码:

#include<iostream>
#include<string>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<queue>
#include<cstring>
#include<map>
using namespace std;
#define M 1000005
typedef long long ll;

int n,c;
ll low,high;
bool vis[M];
ll prime[M/10];
void init()
{
    int m=sqrt(1000000+0.5);
    int i,j;
    c=0;
    for(i=2;i<=m;i++)
    {
        if(!vis[i])
        {
            for(j=i*i;j<=1000000;j+=i)
            {
                vis[j]=true;
            }
        }
    }
    for(i=2;i<=1000000;i++)
    {
        if(!vis[i])
            prime[c++]=(ll)i;
    }
}

int main()
{
    int i;
    ll j;
    init();
    scanf("%d",&n);
    while(n--)
    {
        scanf("%lld%lld",&low,&high);
        ll ans=0;
        for(i=0;i<c;i++)
        {
            if(prime[i]>high)
                break;
            for(j=prime[i]*prime[i];j<=high;j*=prime[i])
            {
                if(j>=low)
                {
                    ans++;
                }
            }
        }
        cout<<ans<<endl;
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值