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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章