|
| 1 | +We will divide this problem into two main cases. |
| 2 | +And show that both cases can be solved in (root(N)) iterations |
| 3 | + |
| 4 | +Either the base is larger than root(N) or smaller than root(N) |
| 5 | + |
| 6 | +When the base is larger than root(N), there are at most two digits. |
| 7 | +Each digit is smaller than root(N). |
| 8 | +Iterate over the first digit and find out the base corresponding to that digit and then the sum of digits. |
| 9 | + |
| 10 | +When the base is smaller than root(N), we can check all of them by brute force |
| 11 | + |
| 12 | +----- |
| 13 | + |
| 14 | +void solve() |
| 15 | +{ |
| 16 | + int n, left, right; |
| 17 | + cin >> n >> left >> right; |
| 18 | + |
| 19 | + int small_base = solve_below_square_root(n, left, right); |
| 20 | + int big_base = solve_above_square_root(n, left, right); |
| 21 | + |
| 22 | + int answer = small_base; |
| 23 | + if(digit_sum(n, small_base) > digit_sum(n, big_base)) |
| 24 | + { |
| 25 | + answer = big_base; |
| 26 | + } |
| 27 | + |
| 28 | + cout << answer << "\n"; |
| 29 | +} |
| 30 | + |
| 31 | +----- |
| 32 | + |
| 33 | +Case 1: b <= root(N) |
| 34 | + |
| 35 | +Let us check all the bases by brute force |
| 36 | + |
| 37 | +----- |
| 38 | + |
| 39 | +int solve_below_square_root(int n, int left, int right) |
| 40 | +{ |
| 41 | + int minimum_sum = digit_sum(n, left), answer = left; |
| 42 | + for(int base = left; base*1LL*base <= n && base <= right; base++) |
| 43 | + { |
| 44 | + if(digit_sum(n, base) < minimum_sum) |
| 45 | + { |
| 46 | + minimum_sum = digit_sum(n, base); |
| 47 | + answer = base; |
| 48 | + } |
| 49 | + |
| 50 | + } |
| 51 | + return answer; |
| 52 | +} |
| 53 | + |
| 54 | +----- |
| 55 | + |
| 56 | +Case 2 : b > root (N) |
| 57 | + |
| 58 | +There can be at most two digits because b^2 > N |
| 59 | + |
| 60 | +N = d1 b + d2 = q. B + r |
| 61 | + |
| 62 | +0 <= p < b < root(N) |
| 63 | + |
| 64 | +The range of each digit is small. |
| 65 | +The beautiful idea is that we will iterate over each possible first digit and then find the corresponding base, |
| 66 | +rather than iterating over the base and then finding the digit. |
| 67 | + |
| 68 | +b = N/p |
| 69 | +r = N (mod B) = N (mod p) |
| 70 | + |
| 71 | +----- |
| 72 | + |
| 73 | +int solve_above_square_root(int n, int left, int right) |
| 74 | +{ |
| 75 | + int minimum_sum = digit_sum(n, right), answer = right; |
| 76 | + //N = digit x B + remainder |
| 77 | + for(int digit = 1; digit*1LL*digit <= n && n/digit >= left; digit++) |
| 78 | + { |
| 79 | + int base = n/digit; |
| 80 | + int remainder = n%base; |
| 81 | + |
| 82 | + if(left <= base && base <= right) |
| 83 | + { |
| 84 | + if(digit + remainder < minimum_sum) |
| 85 | + { |
| 86 | + minimum_sum = digit + remainder; |
| 87 | + answer = base; |
| 88 | + } |
| 89 | + } |
| 90 | + } |
| 91 | + return answer; |
| 92 | +} |
| 93 | + |
0 commit comments