//k root using binary search
#include<iostream>
#include<cmath>
using namespace std;
int kroot(unsigned long long int n,int k)
{
unsigned long long int start=0;
unsigned long long int end=n;
int ans=-1;
while (start<=end)
{
unsigned long long int mid=(start+end)/2;
unsigned long long int o=pow(mid,k);
if (o==n)
{
return mid;
}
if (o<n)
{ ans=mid;
start=mid+1;
}
else
{
end=mid-1;
}
}
/* float inc=0.1;
int precision=3;
for (int i = 0; i < precision; i++)
{
while (ans*ans<n)
{
ans=ans+inc;
}
ans-=inc;
inc=inc/10;
} */
return ans;
}
int main(){
unsigned long long int n;
cin>>n;
int k;
cin>>k;
int ans=kroot(n,k);
cout<<ans;
return 0;
}
Getting wrong answer for larger value of n
overflow may occur because mid^k can be a very large number.(check for case -> 1000000000000000 10 )
use pow function direcly inside if loop without storing it anywhere.
can i store it dynamically??
see this: