Project Euler 346
February 10, 2024
This problem at first seems more intimidating, but it is enough to realize what are the conditions for a number to be a repunit. Then, just need to optimize by noticing what the boundaries of each base are to reduce the time complexity.
Statement
The number is special, because is written in base , and written in base (i.e. ). In other words, is a repunit in at least two bases .
We shall call a positive integer with this property a strong repunit. It can be verified that there are strong repunits below : {}.
Furthermore, the sum of all strong repunits below equals .
Find the sum of all strong repunits below .
Solution
First of all, just take a look that any number can be written as . It means that we only need to find another base , where .
Now, this has already covered all the cases when the length of the repunit is , so the next minimum possible length for the repunit is :
Using just a raw estimation, we can say that .
The strategy for the solution is just to iterate over all the possible bases , and increasing the length of the repunit, then insert any visited number in a set and take the sum of elements in the set. Time complexity for the search of repunits for a base is just , so the total time complexity is just:
Code
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define MAXN 1000000000000
#define N 1000000
set <ll> s;
void solve(){
for(int base=2; base<=N; base++){
ll amount = base+1;
for(int len=2;; len++){
amount *= base;
amount++;
if(amount >= MAXN) break;
s.insert(amount);
}
}
}
ll calculate_sum(){
ll ans = 1;
for(auto v: s) ans += v;
return ans;
}
int main(){
solve();
cout << calculate_sum() << '\n';
return 0;
}