D. Soldier and Number Game(打表)

D. Soldier and Number Game
time limit per test
3 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

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
Copy
2
3 1
6 3
output
2
5

传送门

题意:

    以a!/b!的形式给出一个数字,每次给这个数字除以一个数,求最多可以除多少次。

思路:

    因为题目给的数据范围过大,而且数字的形式是含阶乘的,暴力模拟做绝对行不通的。这么大的数据范围,很多情况下都隐藏着规律,让我们找出规律:

    1.首先a!/b!这种形式,很容易发现,其实就等价于从b+1累乘至a。b!根本不必去考虑,这样就为我们省去了许多计算时间;

    2.再看看题目要求,我们发现,想要一个数n尽可能多次的被除,那每次除数都要尽可能的小,而且要可以整除n。那么满足这些要求的数是什么呢?如果具有一定的数学功底,你一定会敏锐地联想到一类数——质因子!那这样,该问题就转化为求一个正整数n的质因子个数了。

    3.到这里,许许多多像我一样莽撞的年轻人,都想着用常规的方法循环一波求质因子个数,然而这题的数据范围告诉我们没那么简单,要想要让算法在大数字下存活,那就得靠我们的质因子表来解决,在程序开头预先打个表,这样即使碰到大数字,每次也能在O(1)的时间复杂度下输出我们想要的答案。

代码:

#include<bits/stdc++.h>
/*#include<iostream>
#include<stdio.h>
#include<ctype.h>
#include<string>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<climits>
#include<vector>
#include<map>
#include<queue>*/

#define LL long long
#define inf 0x7f7f7f7f

const int N=5000005;

using namespace std;

int yz[N];//质因子表,yz[i]表示 i的质因子个数 

int main()
{	
	int t;
	cin>>t;
	
	memset(yz,0,sizeof(yz));
	
	//生成质因子表 
    for(int i=2;i<N;i++)    
        if(yz[i]==0)    
            for(int j=i;j<N;j+=i)    
                yz[j]=yz[j/i]+1;
				    
    for(int i=1;i<N;i++)    
        yz[i]+=yz[i-1]; 
		
	while(t--)
	{
		int ans=0;
		
		int a,b;
		
		scanf("%d %d",&a,&b);
		
		printf("%d\n",yz[a]-yz[b]);//利用了a!/b!的特性
	}
} 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值