Kth root ques passed 2 testcases but not the last one .I am not getting where i am doing wrong

what i did seems right to me and it passes 2 testcases but not the last one i’m not getting where i am wrong.
Here’s my code–

#include
#include
using namespace std;

double KthRoot(double n,double k) //double becoz pow() works well with double
{
double s=0,e=n,mid,ans;

   while(s<=e)
     {
         mid=(s+e)/2;
         
         if(pow(mid,k)==n)
           {ans=mid;
            break;
            return ceil(ans);
           }
 
         else if(pow(mid,k)<n)
           {
               ans = mid;
               //cout<<ans<<endl;
               s = mid+1;
           }
 
          else
            {
                e = mid-1;
            }
     }
     
     return ceil(ans);   //ceil(x)--rouds off to the closest integer.

}
int main() {
int t;
cin>>t;
double n,k;
while(t)
{

 cin>>n>>k;
 int ans = KthRoot(n,k);
 cout<<ans<<endl;
 t--;
 }
return 0;

}

please help.

Hey Vishnupriya, your code is not giving correct answers for some cases to correct that replace double by long long int in your code and remove the ceil function there is no need of it.

1 Like

thanks @sanjeetboora it worked

but it was written in geeks for geeks that pow() function works well in double only otherwise it is compiler dependent that’s why i used double.So please can anyone clear it out. why its working for long long int now

Hey Vishnupriya , its simple here you are taking mid as a double and if (s+e) results in an odd number mid will be a double then pow(mid,k) will also results in a double and then ceil() will convert it into an int but sometimes using double will give us smaller or larger int value than needed one.

hey @sanjeetboora can you please give an example when double give us smaller or larger int , coz i am a beginner in cpp so it would be helpful for me to understand.
And if possible can you please suggest a good video for data types so that i can find these mistakes in my codes.
TIA!!

You can check for input
1
100 2
If you use double then ur code will give 9 istead of 10.

yeah its giving 9 and if i am making ans variable as int then i am getting 8 . So how are you guys deciding when to take long long int and when int and when double(well in this case i shouldn’t have taken double, i understood as then it will take decimal places and we want only integer part right ??)

There could not any confusion between int and long long as constraints are too large.
But for input 100,2 i am getting 10 And ofcourse it should match for smaller inputs
The question arises when the powoutput crosses the boundary of 10^9 .
Did you get it ?

are you getting 10 after taking ans as an integer??

Yeah ! you can see here
https://ide.codingblocks.com/s/46295
And you should always implement your own power function as it doesnot give correct output format for large values .

yeah its working even without ceil.
Thanks @O17LPOLC0033 :smiley:

1 Like