Soldier and Number Game(素数筛法+前缀和)

Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x > 1, such that n is divisible by x and replacing n with n / x. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.

To make the game more interesting, first soldier chooses n of form a! / b! for some positive integer a and b (a ≥ b). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.

What is the maximum possible score of the second soldier?

Input
First line of input consists of single integer t (1 ≤ t ≤ 1 000 000) denoting number of games soldiers play.

Then follow t lines, each contains pair of integers a and b (1 ≤ b ≤ a ≤ 5 000 000) defining the value of n for a game.

Output
For each game output a maximum score that the second soldier can get.

Examples
Input
2
3 1
6 3
Output
2
5
题目分析:
这个题仔细分析便可知道a!/b!(a>=b)最后b的那一步分是可以约分约掉的,也就是最后范围是a到b+1,那么为了让那个士兵得分最高,那么就需要找到在a到b+1这个范围里每个数变成1需要被它最小的质因子除多少次,最后累加求和便可得到结果。
在刚开始做这个题的时候我完全不懂这个质因子怎么找最快,算是知识盲区,直接写了个最费时的,很明显超时了,最后也是学了一下素数的筛法,这个筛法是越跑越快的。通过这个我也明白cin和cout的速度和scanf和printf的速度不是一个档次的,同样的一个代码,前者能跑三秒多,后者连一秒都没有。

#include<iostream>
#include<iomanip>
#include<cmath>
#include<cstdio>
#include<algorithm>
using namespace std;
const int N=5e6+10;
int prime[N],sum[N];//sum[i]表示从1到i所有质因子的个数
void su()
{
    for(int i=2;i<N;i++)//
    {
        if(!prime[i])//如果这个数没有被访问过
        {
            for(int j=i;j<N;j+=i)//找到以i为最小质因子的所有数
            {
                int temp=j;
                while(temp%i==0)//计算这个数能有多少个质因子
                {
                    sum[j]++;//每找到一个质因子就加一记录
                    temp/=i;
                }
                prime[j]=1;//标记访问
            }
        }
    }
}
int main()
{
    su();//素数打表
    for(int i=2;i<=5000000;i++)//求一下前缀和
        sum[i]=sum[i]+sum[i-1];
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int a,b;
        scanf("%d%d",&a,&b);
        printf("%d\n",sum[a]-sum[b]);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值