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.
Sample test(s)
input
2 3 1 6 3
output
2 5
Dont go by the time limits!!!! Its treacherous!!! When we divide a number continuously by its factors hence it is logical to choose a prime factor and divide continuously as that would give the greatest number of divisions. Hence first we perform a seive and for each prime factor of a number we calculate how long it gets divided .
for example 6=3*2 so the array count[6]=2 similarly count[18]=3 count[20]=3; and so on. since the given number is the form of a!/b! hence we store the prefix sum of all the numbers from 2 to upperbound and then calculate the answer in o(1) using sum[a] - sum[b].
**** code goes here *****
#include<iostream>
#include<stdio.h>
using namespace std;
int sv[5000010];
int sum[5000010];
int count[5000010];
void seive()
{
sv[1]=0;
// cout<<"caleed"<<endl;
for(int i=2;i<=5000001;i++)
{
if(sv[i]==0)
{
// cout<<i<<endl;
for(int j=i;j<=5000001;j+=i)
{
sv[j]=1;
int p=j;
while(p!=0 && p%i==0)
{
count[j]++;
p=p/i;
}
}
}
}
}
int main()
{
seive();
sum[1]=0;
// cout<<count[9]<<" "<<count[10]<<" "<<count[19]<<" "<<count[36]<<" "<<count[30]<<endl;
for(int i=2;i<=5000001;i++)
{
sum[i]=sum[i-1]+count[i];
}
int t;
cin>>t;
int a,b;
while(t--)
{
scanf("%d %d",&a,&b);
int val=sum[a]-sum[b];
printf("%d \n",val);
}
return 0;
}
No comments:
Post a Comment