1 2 3 4 11 12 13 21 22 23 100 1000 5842 0
The 1st humble number is 1. The 2nd humble number is 2. The 3rd humble number is 3. The 4th humble number is 4. The 11th humble number is 12. The 12th humble number is 14. The 13th humble number is 15. The 21st humble number is 28. The 22nd humble number is 30. The 23rd humble number is 32. The 100th humble number is 450. The 1000th humble number is 385875. The 5842nd humble number is 2000000000.
要求的数必定满足 n = 2^a * 3^b * 5^c * 7^d
求第k个满足条件的数,利用动归的思想,每次只取前面记录的最小值,依次类推
#include <iostream> #include <algorithm> #include <cstdio> #include <cstring> #include <cmath> using namespace std; const int NI = 5843; long long dp[NI]; int n, a, b, c, d; long long Min(long long a, long long b, long long c, long long d) { a = min(a, b); a = min(a, c); a = min(a, d); return a; } int main() { a = b = c = d = 0; dp[0] = 1; for(int i = 1; i < NI; i++) { dp[i] = Min(dp[a]*2, dp[b]*3, dp[c]*5, dp[d]*7); if(dp[a]*2 == dp[i]) a++; //2的个数 if(dp[b]*3 == dp[i]) b++; //3的个数 if(dp[c]*5 == dp[i]) c++; //5的个数 if(dp[d]*7 == dp[i]) d++; //7的个数 } while(~scanf("%d", &n) && n) { if(n % 100 == 0 || n % 100 == 11 || n % 100 == 12 || n % 100 == 13) { printf("The %dth humble number is %d.\n", n, dp[n-1]); } else { if(n % 10 == 1) { printf("The %dst humble number is %d.\n", n, dp[n-1]); } else if(n % 10 == 2) { printf("The %dnd humble number is %d.\n", n, dp[n-1]); } else if(n % 10 == 3) { printf("The %drd humble number is %d.\n", n, dp[n-1]); } else { printf("The %dth humble number is %d.\n", n, dp[n-1]); } } } return 0; }
7 13 19 100
26590291
同上题思路是一样的,只是这题的素数是键盘输入得到,因此要先对三个素数从小到大排序
#include <iostream> #include <algorithm> #include <cstdio> #include <cstring> #include <cmath> using namespace std; const int NI = 1e5+5; long long p[3]; long long dp[NI]; int n, a, b, c; long long Min(long long a, long long b, long long c) { a = min(a, b); a = min(a, c); return a; } int main() { while(~scanf("%I64d%I64d%I64d%d", &p[0], &p[1], &p[2], &n)) { a = b = c = 0; dp[0] = 1; for(int i = 1; i <= n; i++) { dp[i] = Min(dp[a]*p[0], dp[b]*p[1], dp[c]*p[2]); if(dp[a]*p[0] == dp[i]) a++; if(dp[b]*p[1] == dp[i]) b++; if(dp[c]*p[2] == dp[i]) c++; } printf("%I64d\n", dp[n]); } return 0; }