Click here to Skip to main content
15,887,596 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C++
#include <bits/stdc++.h>
using namespace std;
#define ll long long
		
		bool condition(ll n, ll k, ll mid){
			ll lhs = pow(mid,k);
			if (lhs <= n){
				return true;
			}
			else return false;
		}


	ll binary_search(ll n, int k){
		ll i = 1;
		ll j = n;
		ll ans = 0;
		while(i<=j){
			ll mid = (i+j)/2;
			if (condition(n,k,mid)){
				ans = mid;
				i = mid+1;
			}
			else {
				j = mid -1;
			}
		}
		return ans;
	}

	int main(){
		int t;
		cin >> t;
		while(t--){
		ll k;
		ll n;
		cin >> n >> k;
		cout << binary_search(n, k) << "\n";
	}


}

You are given two integers n and k. Find the greatest integer x, such that, x^k <= n.

when i give input 10^15 and 10 it returns 10^15 itself but the out put should be 31. Please help me t y.

What I have tried:

tried changing int to long long but it didn't work. :(
Posted
Updated 30-Jan-21 5:29am
v2

Quote:
when i give input 10^15 and 10 it returns 10^15 itself but the out put should be 31.

Your code do not behave the way you expect, or you don't understand why !

There is an almost universal solution: Run your code on debugger step by step, inspect variables.
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't know what your code is supposed to do, it don't find bugs, it just help you to by showing you what is going on. When the code don't do what is expected, you are close to a bug.
To see what your code is doing: Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.

Debugger - Wikipedia, the free encyclopedia[^]

Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]

1.11 — Debugging your program (stepping and breakpoints) | Learn C++[^]

The debugger is here to only show you what your code is doing and your task is to compare with what it should do.
 
Share this answer
 
pow(x, y) is going to overflow even a 64bit value quite soon - e.g. pow(500,10) = ~9.8e26, which is far larger than 2^64 (~1.8e19), so you need another approach. Math can help here: given n^x = m, to solve for x, then x = log(m)/log(n) (Try it on your calculator!).

Hopefully that gives you enough to go on to solve your problem. Of note, the base of the logarithm doesn't matter, you can log10, ln, or log2 or indeed log-basex, and still get the same answer.

Oh, and I used the debugger to figure out why your program was not doing what you wanted it to do, so Patrice's solution is worth noting.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900