/* Consider all integer combinations of ab for 2≤a≤5 and 2≤b≤5: 2^2=4, 2^3=8, 2^4=16, 2^5=32 3^2=9, 3^3=27, 3^4=81, 3^5=243 4^2=16, 4^3=64, 4^4=256, 4^5=1024 5^2=25, 5^3=125, 5^4=625, 5^5=3125 If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms: 4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125 How many distinct terms are in the sequence generated by ab for 2≤a≤100 and 2≤b≤100? */ #include <iostream> #include <set> #include <string> #include <climits> using namespace std; string square(int i, int j) { } int main() { set<string> ss; for (int i=2; i<=100; ++i) { for (int j=2; j<=100; ++j) { string s = square(i, j); ss.insert(s); } } cout << ss.size() << endl; }
搞定,可以扩展至求任意数字的N次方问题
/* Consider all integer combinations of ab for 2≤a≤5 and 2≤b≤5: 2^2=4, 2^3=8, 2^4=16, 2^5=32 3^2=9, 3^3=27, 3^4=81, 3^5=243 4^2=16, 4^3=64, 4^4=256, 4^5=1024 5^2=25, 5^3=125, 5^4=625, 5^5=3125 If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms: 4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125 How many distinct terms are in the sequence generated by ab for 2≤a≤100 and 2≤b≤100? */ #include <iostream> #include <sstream> #include <set> #include <string> #include <climits> #include <vector> using namespace std; typedef unsigned long long I64; const int MAX = 1000000; string square(int x, int y) { int bigNum[34] = {0}; bigNum[0] = x; for (int k=1; k<y; ++k) { for (int i=0; i<34; ++i) { bigNum[i] *= x; } for (int i=0; i<33; ++i) { if (bigNum[i]>=MAX) { int d = bigNum[i] / MAX; bigNum[i] = bigNum[i] % MAX; bigNum[i+1] += d; } } } string os = ""; bool flat = false; for (int i=33; i>=0; --i) { string s; stringstream ss; ss << bigNum[i]; ss >> s; if (s.length()<6) { string zero(6-s.length(),'0'); s = zero + s; } os += s+","; } return os; } int main() { set<string> ss; vector<string> vs; for (int i=2; i<=100; ++i) { for (int j=2; j<=100; ++j) { string s = square(i, j); ss.insert(s); } } cout << ss.size() << endl; cout << square(99,99) << endl; }