File tree Expand file tree Collapse file tree
Problems/Binary-Search/Day-06/sol/Aaryan Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ // link : https://codeforces.com/contest/1846/submission/356025360
2+
3+ #include < iostream>
4+ #include < vector>
5+ #include < cmath>
6+ #include < cstdint>
7+ #include < algorithm>
8+
9+ using namespace std ;
10+
11+ bool check (long long k, int m, long long n) {
12+ __int128 sum = 1 ;
13+ __int128 cur = 1 ;
14+
15+ for (int i = 1 ; i <= m; i++) {
16+ cur *= k;
17+ sum += cur;
18+ if (sum > n) return false ;
19+ }
20+ return sum == n;
21+ }
22+
23+ int main () {
24+ ios::sync_with_stdio (false );
25+ cin.tie (nullptr );
26+
27+ int t;
28+ cin >> t;
29+
30+ while (t--) {
31+ long long n;
32+ cin >> n;
33+
34+ bool possible = false ;
35+
36+ for (int m = 2 ; m <= 60 && !possible; m++) {
37+ long long low = 2 , high = 1e9 ;
38+
39+ while (low <= high) {
40+ long long mid = (low + high) / 2 ;
41+
42+ if (check (mid, m, n)) {
43+ possible = true ;
44+ break ;
45+ }
46+
47+ __int128 sum = 1 , cur = 1 ;
48+ for (int i = 1 ; i <= m; i++) {
49+ cur *= mid;
50+ sum += cur;
51+ if (sum > n) break ;
52+ }
53+
54+ if (sum < n)
55+ low = mid + 1 ;
56+ else
57+ high = mid - 1 ;
58+ }
59+ }
60+
61+ cout << (possible ? " YES\n " : " NO\n " );
62+ }
63+
64+ return 0 ;
65+ }
66+
67+
68+ /*
69+ Explaination:
70+ Try to represent n as a geometric series:
71+ n = 1 + k + k^2 + ... + k^m , where k >= 2 and m >= 2.
72+ Since powers grow fast, we only need to check m up to 60.
73+ For each m, try different values of k using binary search.
74+ For every (k, m), compute the sum iteratively and stop early if it exceeds n.
75+ If any sum equals n, output "YES"; otherwise, output "NO".
76+
77+ Time Complexity:
78+ O(n)
79+
80+ Space Complexity:
81+ O(1)
82+ */
83+
You can’t perform that action at this time.
0 commit comments