Guest User

Untitled

a guest
Aug 21st, 2025
14
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.77 KB | Source Code | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define int long long // force all int → long long
  4. int ilog_ceil(int a, int base) {
  5. int b = 0;
  6. int p = 1;
  7. while (p < a) { // multiply until we reach or exceed a
  8. p *= base;
  9. b++;
  10. }
  11. return b;
  12. }
  13. // integer power function (fast exponentiation)
  14. int ipow(int base, int exp) {
  15. int res = 1;
  16. while (exp > 0) {
  17. if (exp & 1) res *= base;
  18. base *= base;
  19. exp >>= 1;
  20. }
  21. return res;
  22. }
  23.  
  24. // integer log: floor(log_base(n)), assumes base > 1
  25. int ilog(int n, int base) {
  26. int ans = 0;
  27. while (n >= base) {
  28. n /= base;
  29. ans++;
  30. }
  31. return ans;
  32. }
  33.  
  34. // integer ceil division: ceil(a / b), assumes b > 0
  35. int iceil(int a, int b) {
  36. return (a + b - 1) / b;
  37. }
  38.  
  39. signed main() {
  40. int t;
  41. cin >> t;
  42. while (t--) {
  43. int n, k;
  44. cin >> n >> k;
  45.  
  46. int a = n, req = 0;
  47. int ans = 0;
  48.  
  49. while (a) {
  50. int b = ilog(a, 3); // floor(log base 3 of a)
  51.  
  52. if (b == 0) {
  53. ans += 3; // because ipow(3,0+1)=3, and (0 * ipow(3,-1)) = 0
  54. a -= 1; // since c = 3^0 = 1
  55. } else {
  56. ans += ipow(3, b + 1) + (b * ipow(3, b - 1));
  57. int c = ipow(3, b);
  58. a -= c;
  59. }
  60. req++;
  61. }
  62.  
  63. if (k < req) {
  64. cout << -1 << endl;
  65. continue;
  66. }
  67. if (k == req) {
  68. cout << ans << endl;
  69. continue;
  70. }
  71. if (k >= n) {
  72. cout << 3 * n << endl;
  73. continue;
  74. }
  75.  
  76. int inti = iceil(n, k); // safe ceil division
  77. int po = ilog_ceil(inti, 3);
  78.  
  79. int excess = (k * ipow(3, po))-n;
  80.  
  81. map<int, int> m;
  82. m[po]=k;
  83. // cout<<po<<" "<<m[po]<<endl;
  84. while (excess && po != 0) {
  85. int diff = ipow(3, po) - ipow(3, po - 1);
  86. int tobeconv = excess / diff;
  87. if (!tobeconv) break;
  88. m[po - 1] = tobeconv;
  89. m[po] -= tobeconv;
  90. excess -= tobeconv*diff ;
  91. po--;
  92. }
  93. // cout<<excess<<endl;
  94. if(m.find(0)!=m.end()){
  95. if(excess>m[0]){
  96. m[0]=0;
  97. }
  98. else{
  99. m[0]-=excess;
  100. }
  101. }
  102.  
  103. ans = 0;
  104. for (auto &it : m) {
  105. // cout<<it.first<<" "<<it.second<<endl;
  106. if(it.first==0){
  107. ans+= 3*it.second;
  108. }
  109. else{
  110. ans += it.second * (ipow(3, it.first + 1) + (it.first * ipow(3, it.first - 1)));}
  111. }
  112.  
  113. cout << ans << endl; // final output
  114. }
  115. }
  116.  
Advertisement
Add Comment
Please, Sign In to add comment