In this problem it's easy to get TLE while using general approach. here you have to follow one rule which is
1. The total number of divisors of a number is just doubled of divisors till the square root of that number though there's some special case which is if the square root of given number is an integer then the total number of divisors is 2*number of divisors till sqrt(number) -1 otherwise 2*number of divisors till sqrt(number).
for example let a given number is 6 then sqrt(6) = 2.4494 . here 1 and 2 (2 divisors till sqrt(6)) is the divisors till 2.4494(sqrt(6)) and the square root is not an integer(2.4494) so total number of divisors is 2*2=4.
again, let a given number is 25 then sqrt(25) = 5 . here 1 and 5 (2 divisors till sqrt(25)) is the divisors till 5(sqrt(25)) and the square root is an integer(5) so total number of divisors is 2*2-1=3.
similarly you will have to find each number's total number of divisors. then output the number which has largest divisors.
an accepted code is given below:
1. The total number of divisors of a number is just doubled of divisors till the square root of that number though there's some special case which is if the square root of given number is an integer then the total number of divisors is 2*number of divisors till sqrt(number) -1 otherwise 2*number of divisors till sqrt(number).
for example let a given number is 6 then sqrt(6) = 2.4494 . here 1 and 2 (2 divisors till sqrt(6)) is the divisors till 2.4494(sqrt(6)) and the square root is not an integer(2.4494) so total number of divisors is 2*2=4.
again, let a given number is 25 then sqrt(25) = 5 . here 1 and 5 (2 divisors till sqrt(25)) is the divisors till 5(sqrt(25)) and the square root is an integer(5) so total number of divisors is 2*2-1=3.
similarly you will have to find each number's total number of divisors. then output the number which has largest divisors.
an accepted code is given below:
Solution in c++:
- #include<bits/stdc++.h>
- using namespace std;
- int main()
- {
- long long t,a,b,r,j,c,i,temp,value,mx;
- cin>>t;
- while(t--)
- {
- mx=0;
- cin>>a>>b;
- for(i=a; i<=b; i++)
- {
- c=0;
- for(j=1;j<=sqrt(i); j++)
- {
- if(i%j==0)
- {
- c++;
- }
- }
- int temp=sqrt(i);
- if(temp==sqrt(i))
- {
- c=2*c-1;
- }
- else
- {
- c=2*c;
- }
- if(c>mx)
- {
- mx=c;
- value=i;
- }
- }
- printf("Between %lld and %lld, %lld has a maximum of %lld divisors.\n",a,b,value,mx);
- }
- }
No comments