这两道题基本一样就写1338的解题
就是求约数只有2,3,5的数。
思路有点接近动态规划,
用一个变量记录已找到的最大的数,
之后分别记录找到的2,3,5能到的最大的数ans[max]。
这么说还有点玄,实际就是找到之前已找到的答案中
2 * ans[b2]>max, 3 * ans[b3]>max, 5 *ans[b5]>max
三个数中最小的来更新ans[max+1]。
存在数组中之后问什么答什么就可以了。
1338代码
#include<iostream>
#include<Cstdio>
#include<string>
using namespace std;
int res[5843];
int main()
{
int b2 = 1, b3 = 1, b5 = 1, temp;
int big = 1, num;
res[1] = 1;
while(big <= 2000)
{
temp = 2000000001;
while(2 * res[b2] <= res[big])
b2 ++;
if(2 * res[b2] < temp)
temp = 2 * res[b2];
while(3 * res[b3] <= res[big])
b3 ++;
if(3 * res[b3] <= temp)
temp = 3 * res[b3];
while(5 * res[b5] <= res[big])
b5 ++;
if(5 * res[b5] <= temp)
temp = 5 * res[b5];
res[++big] = temp;
}
while(1)
{
scanf("%d", &num);
if(num == 0)
break;
cout << res[num] << endl;
}
return 0;
}
2247的代码
#include<iostream>
#include<Cstdio>
#include<string>
using namespace std;
int res[5843];
int main()
{
int b2 = 1, b3 = 1, b5 = 1, b7 = 1, temp;
int big = 1, num;
res[1] = 1;
while(big <= 5842)
{
temp = 2000000001;
while(2 * res[b2] <= res[big])
b2 ++;
if(2 * res[b2] < temp)
temp = 2 * res[b2];
while(3 * res[b3] <= res[big])
b3 ++;
if(3 * res[b3] <= temp)
temp = 3 * res[b3];
while(5 * res[b5] <= res[big])
b5 ++;
if(5 * res[b5] <= temp)
temp = 5 * res[b5];
while(7 * res[b7] <= res[big])
b7 ++;
if(7 * res[b7] <= temp)
temp = 7 * res[b7];
res[++big] = temp;
}
while(1)
{
scanf("%d", &num);
if(num == 0)
break;
cout << "The " << num;
if(num % 10 == 1)
{
if(num % 100 == 11)
cout << "th humble number is ";
else
cout << "st humble number is ";
}
else if(num % 10 == 2)
{
if(num % 100 == 12)
cout << "th humble number is ";
else
cout << "nd humble number is ";
}
else if(num % 10 == 3)
{
if(num % 100 == 13)
cout << "th humble number is ";
else
cout << "rd humble number is ";
}
else
cout << "th humble number is ";
cout << res[num] << "." << endl;
}
return 0;
}