简体   繁体   English

我怎样才能找到可以写为 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++

So the program must compute all the numbers that can be written as a sum of a power of 2, a power of 3 and a power of 5 below 5.000.000.因此,程序必须计算所有可以写为 2 的幂、3 的幂和 5 的幂的总和,低于 5.000.000。 For example 42 = 16 + 1 + 25 = 2^4 + 3^0 + 5^2.例如 42 = 16 + 1 + 25 = 2^4 + 3^0 + 5^2。 Any idea how can I do this?知道我该怎么做吗?

you can get all powers of 2 and all powers of 3 and all powers of 5 under 5.000.000.您可以在 5.000.000 以下获得 2 的所有幂、3 的所有幂和 5 的所有幂。 first第一的
Then you can try all combinations然后你可以尝试所有组合

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){
            st.insert(power_of_2+power_of_3+power_of_5);
         }
     }
 }
 return vector<int>(st.begin(),st.end());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM