fork download
  1.  
  2.  
  3.  
  4. #include <bits/stdc++.h>
  5. using namespace std;
  6.  
  7. //return 1, if == m:
  8. //return 0, if < m:
  9. //return 2, if > m:
  10. int func(int mid, int n, int m) {
  11. long long ans = 1;
  12. for (int i = 1; i <= n; i++) {
  13. ans = ans * mid;
  14. if (ans > m) return 2;
  15. }
  16. if (ans == m) return 1;
  17. return 0;
  18. }
  19.  
  20. int NthRoot(int n, int m) {
  21. //Use Binary search on the answer space:
  22. int low = 1, high = m;
  23. while (low <= high) {
  24. int mid = (low + high) / 2;
  25. int midN = func(mid, n, m);
  26. if (midN == 1) {
  27. return mid;
  28. }
  29. else if (midN == 0) low = mid + 1;
  30. else high = mid - 1;
  31. }
  32. return -1;
  33. }
  34.  
  35. int main()
  36. {
  37. int n = 3, m = 27;
  38. int ans = NthRoot(n, m);
  39. cout << "The answer is: " << ans << "\n";
  40. return 0;
  41. }
  42.  
  43.  
Success #stdin #stdout 0s 5284KB
stdin
Standard input is empty
stdout
The answer is: 3