我怎样才能找到可以写成 2 的幂、3 的幂和 5 的幂之和的整数? C++
How can i find the integers that can be written as a sum of a power of 2, a power of 3 and a power of 5? C++
因此程序必须计算所有可以写成 5.000.000 以下的 2 次方、3 次方和 5 次方之和的数字。
例如 42 = 16 + 1 + 25 = 2^4 + 3^0 + 5^2。知道我该怎么做吗?
在5.000.000以下,你可以获得2的所有次方和3的所有次方以及5的所有次方。首先
然后你可以尝试所有组合
vector<int> solve(){
const int M = 5000000;
vector<int> p_2={1},p_3={1},p_5={1};
while(p_2.back()*2<M)p_2.push_back(p_2.back()*2);
while(p_3.back()*3<M)p_3.push_back(p_3.back()*3);
while(p_5.back()*5<M)p_5.push_back(p_5.back()*5);
set<int> st;//to remove duplicates
for(auto power_of_2 :p_2){
for(auto power_of_3:p_3){
for(auto power_of_5:p_5){
If(power_of_2+power_of_3+power_of_5<M)
st.insert(power_of_2+power_of_3+power_of_5);
}
}
}
return vector<int>(st.begin(),st.end());
}
因此程序必须计算所有可以写成 5.000.000 以下的 2 次方、3 次方和 5 次方之和的数字。 例如 42 = 16 + 1 + 25 = 2^4 + 3^0 + 5^2。知道我该怎么做吗?
在5.000.000以下,你可以获得2的所有次方和3的所有次方以及5的所有次方。首先
然后你可以尝试所有组合
vector<int> solve(){
const int M = 5000000;
vector<int> p_2={1},p_3={1},p_5={1};
while(p_2.back()*2<M)p_2.push_back(p_2.back()*2);
while(p_3.back()*3<M)p_3.push_back(p_3.back()*3);
while(p_5.back()*5<M)p_5.push_back(p_5.back()*5);
set<int> st;//to remove duplicates
for(auto power_of_2 :p_2){
for(auto power_of_3:p_3){
for(auto power_of_5:p_5){
If(power_of_2+power_of_3+power_of_5<M)
st.insert(power_of_2+power_of_3+power_of_5);
}
}
}
return vector<int>(st.begin(),st.end());
}